Compare commits
2 Commits
templess_b
...
regalloc_c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c43d4984f | ||
|
|
cfe021ff88 |
134
mozilla/ef/Compiler/RegisterAllocator/BitSet.cpp
Normal file
134
mozilla/ef/Compiler/RegisterAllocator/BitSet.cpp
Normal file
@@ -0,0 +1,134 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "BitSet.h"
|
||||
|
||||
// Return the next bit after index set to true or -1 if none.
|
||||
//
|
||||
Int32 BitSet::nextOne(Int32 pos) const
|
||||
{
|
||||
++pos;
|
||||
|
||||
if (pos < 0 || Uint32(pos) >= universeSize)
|
||||
return -1;
|
||||
|
||||
Uint32 offset = getWordOffset(pos);
|
||||
Uint8 index = getBitOffset(pos);
|
||||
Word* ptr = &word[offset];
|
||||
Word currentWord = *ptr++ >> index;
|
||||
|
||||
if (currentWord != Word(0)) {
|
||||
while ((currentWord & Word(1)) == 0) {
|
||||
++index;
|
||||
currentWord >>= 1;
|
||||
}
|
||||
return (offset << nBitsInWordLog2) + index;
|
||||
}
|
||||
|
||||
Word* limit = &word[getSizeInWords(universeSize)];
|
||||
while (ptr < limit) {
|
||||
++offset;
|
||||
currentWord = *ptr++;
|
||||
if (currentWord != Word(0)) {
|
||||
index = 0;
|
||||
while ((currentWord & Word(1)) == 0) {
|
||||
++index;
|
||||
currentWord >>= 1;
|
||||
}
|
||||
return (offset << nBitsInWordLog2) + index;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Return the next bit after index set to false or -1 if none.
|
||||
//
|
||||
Int32 BitSet::nextZero(Int32 pos) const
|
||||
{
|
||||
++pos;
|
||||
|
||||
if (pos < 0 || Uint32(pos) >= universeSize)
|
||||
return -1;
|
||||
|
||||
Uint32 offset = getWordOffset(pos);
|
||||
Uint8 index = getBitOffset(pos);
|
||||
Word* ptr = &word[offset];
|
||||
Word currentWord = *ptr++ >> index;
|
||||
|
||||
if (currentWord != Word(~0)) {
|
||||
for (; index < nBitsInWord; ++index) {
|
||||
if ((currentWord & Word(1)) == 0) {
|
||||
Int32 ret = (offset << nBitsInWordLog2) + index;
|
||||
return (Uint32(ret) < universeSize) ? ret : -1;
|
||||
}
|
||||
currentWord >>= 1;
|
||||
}
|
||||
}
|
||||
|
||||
Word* limit = &word[getSizeInWords(universeSize)];
|
||||
while (ptr < limit) {
|
||||
++offset;
|
||||
currentWord = *ptr++;
|
||||
if (currentWord != Word(~0)) {
|
||||
for (index = 0; index < nBitsInWord; ++index) {
|
||||
if ((currentWord & Word(1)) == 0) {
|
||||
Int32 ret = (offset << nBitsInWordLog2) + index;
|
||||
return (Uint32(ret) < universeSize) ? ret : -1;
|
||||
}
|
||||
currentWord >>= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
|
||||
// Print the set.
|
||||
//
|
||||
void BitSet::printPretty(LogModuleObject log)
|
||||
{
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("[ "));
|
||||
|
||||
for (Int32 i = firstOne(); i != -1; i = nextOne(i)) {
|
||||
Int32 currentBit = i;
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%d", currentBit));
|
||||
|
||||
Int32 nextBit = nextOne(currentBit);
|
||||
if (nextBit != currentBit + 1) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" "));
|
||||
continue;
|
||||
}
|
||||
|
||||
while ((nextBit != -1) && (nextBit == (currentBit + 1))) {
|
||||
currentBit = nextBit;
|
||||
nextBit = nextOne(nextBit);
|
||||
}
|
||||
|
||||
if (currentBit > (i+1))
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("-%d ", currentBit));
|
||||
else
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" %d ", currentBit));
|
||||
|
||||
i = currentBit;
|
||||
}
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("]\n"));
|
||||
}
|
||||
|
||||
#endif // DEBUG_LOG
|
||||
195
mozilla/ef/Compiler/RegisterAllocator/BitSet.h
Normal file
195
mozilla/ef/Compiler/RegisterAllocator/BitSet.h
Normal file
@@ -0,0 +1,195 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _BITSET_H_
|
||||
#define _BITSET_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "LogModule.h"
|
||||
#include "Pool.h"
|
||||
#include <string.h>
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// BitSet -
|
||||
|
||||
class BitSet
|
||||
{
|
||||
private:
|
||||
|
||||
#if (PR_BITS_PER_WORD == 64)
|
||||
typedef Uint64 Word;
|
||||
#elif (PR_BITS_PER_WORD == 32)
|
||||
typedef Uint32 Word;
|
||||
#endif
|
||||
|
||||
static const nBitsInWord = PR_BITS_PER_WORD;
|
||||
static const nBytesInWord = PR_BYTES_PER_WORD;
|
||||
static const nBitsInWordLog2 = PR_BITS_PER_WORD_LOG2;
|
||||
static const nBytesInWordLog2 = PR_BYTES_PER_WORD_LOG2;
|
||||
|
||||
// Return the number of Word need to store the universe.
|
||||
static Uint32 getSizeInWords(Uint32 sizeOfUniverse) {return (sizeOfUniverse + (nBitsInWord - 1)) >> nBitsInWordLog2;}
|
||||
// Return the given element offset in its containing Word.
|
||||
static Uint32 getBitOffset(Uint32 element) {return element & (nBitsInWord - 1);}
|
||||
// Return the Word offset for the given element int the universe.
|
||||
static Uint32 getWordOffset(Uint32 element) {return element >> nBitsInWordLog2;}
|
||||
// Return the mask for the given bit index.
|
||||
static Word getMask(Uint8 index) {return Word(1) << index;}
|
||||
|
||||
private:
|
||||
|
||||
Uint32 universeSize; // Size of the universe
|
||||
Word* word; // universe memory.
|
||||
|
||||
private:
|
||||
|
||||
// No copy constructor.
|
||||
BitSet(const BitSet&);
|
||||
|
||||
// Check if the given set's universe is of the same size than this universe.
|
||||
void checkUniverseCompatibility(const BitSet& set) const {assert(set.universeSize == universeSize);}
|
||||
// Check if pos is valid for this set's universe.
|
||||
void checkMember(Int32 pos) const {assert(pos >=0 && Uint32(pos) < universeSize);}
|
||||
|
||||
public:
|
||||
|
||||
// Create a bitset of universeSize bits.
|
||||
BitSet(Pool& pool, Uint32 universeSize) : universeSize(universeSize) {word = new(pool) Word[getSizeInWords(universeSize)]; clear();}
|
||||
|
||||
// Return the size of this bitset.
|
||||
Uint32 getSize() const {return universeSize;}
|
||||
|
||||
// Clear the bitset.
|
||||
void clear() {memset(word, 0x00, getSizeInWords(universeSize) << nBytesInWordLog2);}
|
||||
// Clear the bit at index.
|
||||
void clear(Uint32 index) {checkMember(index); word[getWordOffset(index)] &= ~getMask(index);}
|
||||
// Set the bitset.
|
||||
void set() {memset(word, 0xFF, getSizeInWords(universeSize) << nBytesInWordLog2);}
|
||||
// Set the bit at index.
|
||||
void set(Uint32 index) {checkMember(index); word[getWordOffset(index)] |= getMask(index);}
|
||||
// Return true if the bit at index is set.
|
||||
bool test(Uint32 index) const {checkMember(index); return (word[getWordOffset(index)] & getMask(index)) != 0;}
|
||||
// Union with the given bitset.
|
||||
inline void or(const BitSet& set);
|
||||
// Intersection with the given bitset.
|
||||
inline void and(const BitSet& set);
|
||||
// Difference with the given bitset.
|
||||
inline void difference(const BitSet& set);
|
||||
// Copy set.
|
||||
inline BitSet& operator = (const BitSet& set);
|
||||
// Return true if the bitset are identical.
|
||||
friend bool operator == (const BitSet& set1, const BitSet& set2);
|
||||
// Return true if the bitset are different.
|
||||
friend bool operator != (const BitSet& set1, const BitSet& set2);
|
||||
|
||||
// Logical operators.
|
||||
BitSet& operator |= (const BitSet& set) {or(set); return *this;}
|
||||
BitSet& operator &= (const BitSet& set) {and(set); return *this;}
|
||||
BitSet& operator -= (const BitSet& set) {difference(set); return *this;}
|
||||
|
||||
// Return the first bit at set to true or -1 if none.
|
||||
Int32 firstOne() const {return nextOne(-1);}
|
||||
// Return the next bit after index set to true or -1 if none.
|
||||
Int32 nextOne(Int32 pos) const;
|
||||
// Return the first bit at set to false or -1 if none.
|
||||
Int32 firstZero() const {return nextZero(-1);}
|
||||
// Return the next bit after index set to false or -1 if none.
|
||||
Int32 nextZero(Int32 pos) const;
|
||||
|
||||
// Iterator to conform with the set API.
|
||||
typedef Int32 iterator;
|
||||
// Return true if the walk is ordered.
|
||||
static bool isOrdered() {return true;}
|
||||
// Return the iterator for the first element of this set.
|
||||
iterator begin() const {return firstOne();}
|
||||
// Return the next iterator.
|
||||
iterator advance(iterator pos) const {return nextOne(pos);}
|
||||
// Return true if the iterator is at the end of the set.
|
||||
bool done(iterator pos) const {return pos == -1;}
|
||||
// Return the element corresponding to the given iterator.
|
||||
Uint32 get(iterator pos) const {return pos;}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
// Print the set.
|
||||
void printPretty(LogModuleObject log);
|
||||
#endif // DEBUG_LOG
|
||||
};
|
||||
|
||||
// Union with the given bitset.
|
||||
//
|
||||
inline void BitSet::or(const BitSet& set)
|
||||
{
|
||||
checkUniverseCompatibility(set);
|
||||
Word* src = set.word;
|
||||
Word* dst = word;
|
||||
Word* limit = &src[getSizeInWords(universeSize)];
|
||||
|
||||
while (src < limit)
|
||||
*dst++ |= *src++;
|
||||
}
|
||||
|
||||
// Intersection with the given bitset.
|
||||
//
|
||||
inline void BitSet::and(const BitSet& set)
|
||||
{
|
||||
checkUniverseCompatibility(set);
|
||||
Word* src = set.word;
|
||||
Word* dst = word;
|
||||
Word* limit = &src[getSizeInWords(universeSize)];
|
||||
|
||||
while (src < limit)
|
||||
*dst++ &= *src++;
|
||||
}
|
||||
|
||||
// Difference with the given bitset.
|
||||
//
|
||||
inline void BitSet::difference(const BitSet& set)
|
||||
{
|
||||
checkUniverseCompatibility(set);
|
||||
Word* src = set.word;
|
||||
Word* dst = word;
|
||||
Word* limit = &src[getSizeInWords(universeSize)];
|
||||
|
||||
while (src < limit)
|
||||
*dst++ &= ~*src++;
|
||||
}
|
||||
|
||||
// Copy the given set into this set.
|
||||
//
|
||||
inline BitSet& BitSet::operator = (const BitSet& set)
|
||||
{
|
||||
checkUniverseCompatibility(set);
|
||||
if (this != &set)
|
||||
memcpy(word, set.word, getSizeInWords(universeSize) << nBytesInWordLog2);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Return true if the given set is identical to this set.
|
||||
inline bool operator == (const BitSet& set1, const BitSet& set2)
|
||||
{
|
||||
set1.checkUniverseCompatibility(set2);
|
||||
|
||||
if (&set1 == &set2)
|
||||
return true;
|
||||
|
||||
return memcmp(set1.word, set2.word, BitSet::getSizeInWords(set1.universeSize) << BitSet::nBytesInWordLog2) == 0;
|
||||
}
|
||||
|
||||
inline bool operator != (const BitSet& set1, const BitSet& set2) {return !(set1 == set2);}
|
||||
|
||||
#endif // _BITSET_H
|
||||
159
mozilla/ef/Compiler/RegisterAllocator/Coalescing.h
Normal file
159
mozilla/ef/Compiler/RegisterAllocator/Coalescing.h
Normal file
@@ -0,0 +1,159 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _COALESCING_H_
|
||||
#define _COALESCING_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "Pool.h"
|
||||
#include "RegisterPressure.h"
|
||||
#include "InterferenceGraph.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "ControlNodes.h"
|
||||
#include "Instruction.h"
|
||||
#include "SparseSet.h"
|
||||
#include "RegisterAllocator.h"
|
||||
#include "RegisterAllocatorTools.h"
|
||||
|
||||
#if 1
|
||||
// Performing an ultra conservative coalescing meens that when we look at
|
||||
// candidates (source,destination) for coalescing we need to make sure
|
||||
// that the combined interference of the source and destination register
|
||||
// will not exceed the total number of register available for the register
|
||||
// class.
|
||||
#define ULTRA_CONSERVATIVE_COALESCING
|
||||
#else
|
||||
// If we are not doing an ultra conservative coalescing we have to make sure
|
||||
// that the total number of neighbor whose degree is greater than the total
|
||||
// number of register is not greater than the total number of register.
|
||||
#undef ULTRA_CONSERVATIVE_COALESCING
|
||||
#endif
|
||||
|
||||
template <class RegisterPressure>
|
||||
struct Coalescing
|
||||
{
|
||||
static bool coalesce(RegisterAllocator& registerAllocator);
|
||||
};
|
||||
|
||||
template <class RegisterPressure>
|
||||
bool Coalescing<RegisterPressure>::coalesce(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
Pool& pool = registerAllocator.pool;
|
||||
|
||||
// Initialize the lookup table
|
||||
//
|
||||
Uint32 rangeCount = registerAllocator.rangeCount;
|
||||
RegisterName* newRange = new RegisterName[2 * rangeCount];
|
||||
RegisterName* coalescedRange = &newRange[rangeCount];
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
|
||||
init(coalescedRange, rangeCount);
|
||||
|
||||
SparseSet interferences(pool, rangeCount);
|
||||
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
|
||||
bool removedInstructions = false;
|
||||
|
||||
ControlGraph& controlGraph = registerAllocator.controlGraph;
|
||||
ControlNode** nodes = controlGraph.lndList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
|
||||
// Walk the nodes in the loop nesting depth list.
|
||||
for (Int32 n = nNodes - 1; n >= 0; n--) {
|
||||
InstructionList& instructions = nodes[n]->getInstructions();
|
||||
|
||||
InstructionList::iterator it = instructions.begin();
|
||||
while (!instructions.done(it)) {
|
||||
Instruction& instruction = instructions.get(it);
|
||||
it = instructions.advance(it);
|
||||
|
||||
if ((instruction.getFlags() & ifCopy) != 0) {
|
||||
assert(instruction.getInstructionUseBegin() != instruction.getInstructionUseEnd() && instruction.getInstructionUseBegin()[0].isRegister());
|
||||
assert(instruction.getInstructionDefineBegin() != instruction.getInstructionDefineEnd() && instruction.getInstructionDefineBegin()[0].isRegister());
|
||||
|
||||
RegisterName source = findRoot(name2range[instruction.getInstructionUseBegin()[0].getRegisterName()], coalescedRange);
|
||||
RegisterName destination = findRoot(name2range[instruction.getInstructionDefineBegin()[0].getRegisterName()], coalescedRange);
|
||||
|
||||
if (source == destination) {
|
||||
instruction.remove();
|
||||
} else if (!iGraph.interfere(source, destination)) {
|
||||
InterferenceVector* sourceVector = iGraph.getInterferenceVector(source);
|
||||
InterferenceVector* destinationVector = iGraph.getInterferenceVector(destination);
|
||||
|
||||
#ifdef ULTRA_CONSERVATIVE_COALESCING
|
||||
interferences.clear();
|
||||
|
||||
InterferenceVector* vector;
|
||||
for (vector = sourceVector; vector != NULL; vector = vector->next) {
|
||||
RegisterName* neighbors = vector->neighbors;
|
||||
for (Uint32 i = 0; i < vector->count; i++)
|
||||
interferences.set(findRoot(neighbors[i], coalescedRange));
|
||||
}
|
||||
for (vector = destinationVector; vector != NULL; vector = vector->next) {
|
||||
RegisterName* neighbors = vector->neighbors;
|
||||
for (Uint32 i = 0; i < vector->count; i++)
|
||||
interferences.set(findRoot(neighbors[i], coalescedRange));
|
||||
}
|
||||
|
||||
Uint32 count = interferences.getSize();
|
||||
#else // ULTRA_CONSERVATIVE_COALESCING
|
||||
trespass("not implemented");
|
||||
Uint32 count = 0;
|
||||
#endif // ULTRA_CONSERVATIVE_COALESCING
|
||||
|
||||
if (count < 6 /* FIX: should get the number from the class */) {
|
||||
// Update the interferences vector.
|
||||
if (sourceVector == NULL) {
|
||||
iGraph.setInterferenceVector(source, destinationVector);
|
||||
sourceVector = destinationVector;
|
||||
} else if (destinationVector == NULL)
|
||||
iGraph.setInterferenceVector(destination, sourceVector);
|
||||
else {
|
||||
InterferenceVector* last = NULL;
|
||||
for (InterferenceVector* v = sourceVector; v != NULL; v = v->next)
|
||||
last = v;
|
||||
assert(last);
|
||||
last->next = destinationVector;
|
||||
iGraph.setInterferenceVector(destination, sourceVector);
|
||||
}
|
||||
// Update the interference matrix.
|
||||
for (InterferenceVector* v = sourceVector; v != NULL; v = v->next) {
|
||||
RegisterName* neighbors = v->neighbors;
|
||||
for (Uint32 i = 0; i < v->count; i++) {
|
||||
RegisterName neighbor = findRoot(neighbors[i], coalescedRange);
|
||||
iGraph.setInterference(neighbor, source);
|
||||
iGraph.setInterference(neighbor, destination);
|
||||
}
|
||||
}
|
||||
|
||||
instruction.remove();
|
||||
coalescedRange[source] = destination;
|
||||
removedInstructions = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAllocator.rangeCount = compress(registerAllocator.name2range, coalescedRange, registerAllocator.nameCount, rangeCount);
|
||||
delete newRange;
|
||||
|
||||
return removedInstructions;
|
||||
}
|
||||
|
||||
#endif // _COALESCING_H_
|
||||
283
mozilla/ef/Compiler/RegisterAllocator/Coloring.cpp
Normal file
283
mozilla/ef/Compiler/RegisterAllocator/Coloring.cpp
Normal file
@@ -0,0 +1,283 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef NEW_LAURENTM_CODE
|
||||
|
||||
#include "Coloring.h"
|
||||
#include "VirtualRegister.h"
|
||||
#include "FastBitSet.h"
|
||||
#include "FastBitMatrix.h"
|
||||
#include "CpuInfo.h"
|
||||
|
||||
bool Coloring::
|
||||
assignRegisters(FastBitMatrix& interferenceMatrix)
|
||||
{
|
||||
PRUint32 *stackPtr = new(pool) PRUint32[vRegManager.count()];
|
||||
|
||||
return select(interferenceMatrix, stackPtr, simplify(interferenceMatrix, stackPtr));
|
||||
}
|
||||
|
||||
PRInt32 Coloring::
|
||||
getLowestSpillCostRegister(FastBitSet& bitset)
|
||||
{
|
||||
PRInt32 lowest = bitset.firstOne();
|
||||
if (lowest != -1)
|
||||
{
|
||||
Flt32 cost = vRegManager.getVirtualRegister(lowest).spillInfo.spillCost;
|
||||
for (PRInt32 r = bitset.nextOne(lowest); r != -1; r = bitset.nextOne(r))
|
||||
{
|
||||
VirtualRegister& vReg = vRegManager.getVirtualRegister(r);
|
||||
if (!vReg.spillInfo.infiniteSpillCost && (vReg.spillInfo.spillCost < cost))
|
||||
{
|
||||
cost = vReg.spillInfo.spillCost;
|
||||
lowest = r;
|
||||
}
|
||||
}
|
||||
}
|
||||
return lowest;
|
||||
}
|
||||
|
||||
PRUint32* Coloring::
|
||||
simplify(FastBitMatrix interferenceMatrix, PRUint32* stackPtr)
|
||||
{
|
||||
// first we construct the sets low and high. low contains all nodes of degree
|
||||
// inferior to the number of register available on the processor. All the
|
||||
// nodes with an high degree and a finite spill cost are placed in high.
|
||||
// Nodes of high degree and infinite spill cost are not included in either sets.
|
||||
|
||||
PRUint32 nRegisters = vRegManager.count();
|
||||
FastBitSet low(pool, nRegisters);
|
||||
FastBitSet high(pool, nRegisters);
|
||||
FastBitSet stack(pool, nRegisters);
|
||||
|
||||
for (VirtualRegisterManager::iterator i = vRegManager.begin(); !vRegManager.done(i); i = vRegManager.advance(i))
|
||||
{
|
||||
VirtualRegister& vReg = vRegManager.getVirtualRegister(i);
|
||||
|
||||
if (vReg.getClass() == vrcStackSlot)
|
||||
{
|
||||
stack.set(i);
|
||||
vReg.colorRegister(nRegisters);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (vReg.colorInfo.interferenceDegree < NUMBER_OF_REGISTERS)
|
||||
low.set(i);
|
||||
else // if (!vReg.spillInfo.infiniteSpillCost)
|
||||
high.set(i);
|
||||
|
||||
// Set coloring info.
|
||||
vReg.spillInfo.willSpill = false;
|
||||
|
||||
switch(vReg.getClass())
|
||||
{
|
||||
case vrcInteger:
|
||||
vReg.colorRegister(LAST_GREGISTER + 1);
|
||||
break;
|
||||
case vrcFloatingPoint:
|
||||
case vrcFixedPoint:
|
||||
vReg.colorRegister(LAST_FPREGISTER + 1);
|
||||
break;
|
||||
default:
|
||||
PR_ASSERT(false); // Cannot happen.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// push the stack registers
|
||||
PRInt32 j;
|
||||
for (j = stack.firstOne(); j != -1; j = stack.nextOne(j))
|
||||
*stackPtr++ = j;
|
||||
|
||||
// simplify
|
||||
while (true)
|
||||
{
|
||||
PRInt32 r;
|
||||
while ((r = getLowestSpillCostRegister(low)) != -1)
|
||||
{
|
||||
VirtualRegister& vReg = vRegManager.getVirtualRegister(r);
|
||||
|
||||
/* update low and high */
|
||||
FastBitSet inter(interferenceMatrix.getRow(r), nRegisters);
|
||||
for (j = inter.firstOne(); j != -1; j = inter.nextOne(j))
|
||||
{
|
||||
VirtualRegister& neighbor = vRegManager.getVirtualRegister(j);
|
||||
// if the new interference degree of one of his neighbor becomes
|
||||
// NUMBER_OF_REGISTERS - 1 then it is added to the set 'low'.
|
||||
|
||||
PRUint32 maxInterference = 0;
|
||||
switch (neighbor.getClass())
|
||||
{
|
||||
case vrcInteger:
|
||||
maxInterference = NUMBER_OF_GREGISTERS;
|
||||
break;
|
||||
case vrcFloatingPoint:
|
||||
case vrcFixedPoint:
|
||||
maxInterference = NUMBER_OF_FPREGISTERS;
|
||||
break;
|
||||
default:
|
||||
PR_ASSERT(false);
|
||||
}
|
||||
if ((vRegManager.getVirtualRegister(j).colorInfo.interferenceDegree-- == maxInterference))
|
||||
{
|
||||
high.clear(j);
|
||||
low.set(j);
|
||||
}
|
||||
vReg.colorInfo.interferenceDegree--;
|
||||
interferenceMatrix.clear(r, j);
|
||||
interferenceMatrix.clear(j, r);
|
||||
}
|
||||
low.clear(r);
|
||||
|
||||
// Push this register.
|
||||
*stackPtr++ = r;
|
||||
}
|
||||
if ((r = getLowestSpillCostRegister(high)) != -1)
|
||||
{
|
||||
high.clear(r);
|
||||
low.set(r);
|
||||
}
|
||||
else
|
||||
break;
|
||||
}
|
||||
|
||||
return stackPtr;
|
||||
}
|
||||
|
||||
bool Coloring::
|
||||
select(FastBitMatrix& interferenceMatrix, PRUint32* stackBase, PRUint32* stackPtr)
|
||||
{
|
||||
PRUint32 nRegisters = vRegManager.count();
|
||||
FastBitSet usedRegisters(NUMBER_OF_REGISTERS + 1); // usedRegisters if used for both GR & FPR.
|
||||
FastBitSet preColoredRegisters(NUMBER_OF_REGISTERS + 1);
|
||||
FastBitSet usedStack(nRegisters + 1);
|
||||
bool success = true;
|
||||
Int32 lastUsedSSR = -1;
|
||||
|
||||
// select
|
||||
while (stackPtr != stackBase)
|
||||
{
|
||||
// Pop one register.
|
||||
PRUint32 r = *--stackPtr;
|
||||
VirtualRegister& vReg = vRegManager.getVirtualRegister(r);
|
||||
|
||||
FastBitSet neighbors(interferenceMatrix.getRow(r), nRegisters);
|
||||
|
||||
if (vReg.getClass() == vrcStackSlot)
|
||||
// Stack slots coloring.
|
||||
{
|
||||
usedStack.clear();
|
||||
|
||||
for (PRInt32 i = neighbors.firstOne(); i != -1; i = neighbors.nextOne(i))
|
||||
usedStack.set(vRegManager.getVirtualRegister(i).getColor());
|
||||
|
||||
Int32 color = usedStack.firstZero();
|
||||
vReg.colorRegister(color);
|
||||
if (color > lastUsedSSR)
|
||||
lastUsedSSR = color;
|
||||
}
|
||||
else
|
||||
// Integer & Floating point register coloring.
|
||||
{
|
||||
usedRegisters.clear();
|
||||
preColoredRegisters.clear();
|
||||
|
||||
for (PRInt32 i = neighbors.firstOne(); i != -1; i = neighbors.nextOne(i))
|
||||
{
|
||||
VirtualRegister& nvReg = vRegManager.getVirtualRegister(i);
|
||||
usedRegisters.set(nvReg.getColor());
|
||||
if (nvReg.isPreColored())
|
||||
preColoredRegisters.set(nvReg.getPreColor());
|
||||
}
|
||||
if (vReg.hasSpecialInterference)
|
||||
usedRegisters |= vReg.specialInterference;
|
||||
|
||||
PRInt8 c = -1;
|
||||
PRInt8 maxColor = 0;
|
||||
PRInt8 firstColor = 0;
|
||||
switch (vReg.getClass())
|
||||
{
|
||||
case vrcInteger:
|
||||
firstColor = FIRST_GREGISTER;
|
||||
maxColor = LAST_GREGISTER;
|
||||
break;
|
||||
case vrcFloatingPoint:
|
||||
case vrcFixedPoint:
|
||||
firstColor = FIRST_FPREGISTER;
|
||||
maxColor = LAST_FPREGISTER;
|
||||
break;
|
||||
default:
|
||||
PR_ASSERT(false);
|
||||
}
|
||||
|
||||
if (vReg.isPreColored())
|
||||
{
|
||||
c = vReg.getPreColor();
|
||||
if (usedRegisters.test(c))
|
||||
c = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (c = usedRegisters.nextZero(firstColor - 1); (c >= 0) && (c <= maxColor) && (preColoredRegisters.test(c));
|
||||
c = usedRegisters.nextZero(c)) {}
|
||||
}
|
||||
|
||||
if ((c >= 0) && (c <= maxColor))
|
||||
{
|
||||
vReg.colorRegister(c);
|
||||
}
|
||||
else
|
||||
{
|
||||
VirtualRegister& stackRegister = vRegManager.newVirtualRegister(vrcStackSlot);
|
||||
vReg.equivalentRegister[vrcStackSlot] = &stackRegister;
|
||||
vReg.spillInfo.willSpill = true;
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG
|
||||
if (success)
|
||||
{
|
||||
for (VirtualRegisterManager::iterator i = vRegManager.begin(); !vRegManager.done(i); i = vRegManager.advance(i))
|
||||
{
|
||||
VirtualRegister& vReg = vRegManager.getVirtualRegister(i);
|
||||
switch (vReg.getClass())
|
||||
{
|
||||
case vrcInteger:
|
||||
if (vReg.getColor() > LAST_GREGISTER)
|
||||
PR_ASSERT(false);
|
||||
break;
|
||||
case vrcFloatingPoint:
|
||||
case vrcFixedPoint:
|
||||
#if NUMBER_OF_FPREGISTERS != 0
|
||||
if (vReg.getColor() > LAST_FPREGISTER)
|
||||
PR_ASSERT(false);
|
||||
#endif
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
vRegManager.nUsedStackSlots = lastUsedSSR + 1;
|
||||
return success;
|
||||
}
|
||||
#endif // NEW_LAURENTM_CODE
|
||||
284
mozilla/ef/Compiler/RegisterAllocator/Coloring.h
Normal file
284
mozilla/ef/Compiler/RegisterAllocator/Coloring.h
Normal file
@@ -0,0 +1,284 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "ControlNodes.h"
|
||||
#include "Instruction.h"
|
||||
#include "RegisterAllocator.h"
|
||||
#include "VirtualRegister.h"
|
||||
#include "InterferenceGraph.h"
|
||||
#include "SparseSet.h"
|
||||
#include "Spilling.h"
|
||||
#include "Splits.h"
|
||||
|
||||
UT_EXTERN_LOG_MODULE(RegAlloc);
|
||||
|
||||
template <class RegisterPressure>
|
||||
class Coloring
|
||||
{
|
||||
private:
|
||||
static RegisterName* simplify(RegisterAllocator& registerAllocator, RegisterName* coloringStack);
|
||||
static bool select(RegisterAllocator& registerAllocator, RegisterName* coloringStack, RegisterName* coloringStackPtr);
|
||||
|
||||
public:
|
||||
static bool color(RegisterAllocator& registerAllocator);
|
||||
static void finalColoring(RegisterAllocator& registerAllocator);
|
||||
};
|
||||
|
||||
|
||||
template <class RegisterPressure>
|
||||
void Coloring<RegisterPressure>::finalColoring(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
RegisterName* color = registerAllocator.color;
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
|
||||
ControlGraph& controlGraph = registerAllocator.controlGraph;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
InstructionList& instructions = nodes[n]->getInstructions();
|
||||
|
||||
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
usePtr->setRegisterName(color[name2range[usePtr->getRegisterName()]]);
|
||||
#ifdef DEBUG
|
||||
RegisterID rid = usePtr->getRegisterID();
|
||||
setColoredRegister(rid);
|
||||
usePtr->setRegisterID(rid);
|
||||
#endif // DEBUG
|
||||
}
|
||||
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister()) {
|
||||
definePtr->setRegisterName(color[name2range[definePtr->getRegisterName()]]);
|
||||
#ifdef DEBUG
|
||||
RegisterID rid = definePtr->getRegisterID();
|
||||
setColoredRegister(rid);
|
||||
definePtr->setRegisterID(rid);
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
bool Coloring<RegisterPressure>::select(RegisterAllocator& registerAllocator, RegisterName* coloringStack, RegisterName* coloringStackPtr)
|
||||
{
|
||||
Uint32 rangeCount = registerAllocator.rangeCount;
|
||||
RegisterName* color = new RegisterName[rangeCount];
|
||||
registerAllocator.color = color;
|
||||
|
||||
for (Uint32 r = 1; r < rangeCount; r++)
|
||||
color[r] = RegisterName(6); // FIX;
|
||||
|
||||
// Color the preColored registers.
|
||||
//
|
||||
VirtualRegisterManager& vrManager = registerAllocator.vrManager;
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
PreColoredRegister* machineEnd = vrManager.getMachineRegistersEnd();
|
||||
for (PreColoredRegister* machinePtr = vrManager.getMachineRegistersBegin(); machinePtr < machineEnd; machinePtr++)
|
||||
if (machinePtr->id != invalidID) {
|
||||
color[name2range[getName(machinePtr->id)]] = machinePtr->color;
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\twill preColor range %d as %d\n", name2range[getName(machinePtr->id)], machinePtr->color));
|
||||
}
|
||||
|
||||
SpillCost* cost = registerAllocator.spillCost;
|
||||
Pool& pool = registerAllocator.pool;
|
||||
SparseSet& spill = *new(pool) SparseSet(pool, rangeCount);
|
||||
registerAllocator.willSpill = &spill;
|
||||
SparseSet neighborColors(pool, 6); // FIX
|
||||
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
|
||||
|
||||
bool coloringFailed = false;
|
||||
while (coloringStackPtr > coloringStack) {
|
||||
RegisterName range = *--coloringStackPtr;
|
||||
|
||||
if (!cost[range].infinite && cost[range].cost < 0) {
|
||||
coloringFailed = true;
|
||||
spill.set(range);
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tfailed to color %d, will spill.\n", range));
|
||||
} else {
|
||||
neighborColors.clear();
|
||||
|
||||
for (InterferenceVector* vector = iGraph.getInterferenceVector(range); vector != NULL; vector = vector->next)
|
||||
for (Int32 i = vector->count - 1; i >= 0; --i) {
|
||||
RegisterName neighborColor = color[vector->neighbors[i]];
|
||||
if (neighborColor < 6) // FIX
|
||||
neighborColors.set(neighborColor);
|
||||
}
|
||||
|
||||
if (neighborColors.getSize() == 6) { // FIX
|
||||
coloringFailed = true;
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tfailed to color %d, ", range));
|
||||
|
||||
if (!Splits<RegisterPressure>::findSplit(registerAllocator, color, range)) {
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("will spill.\n"));
|
||||
spill.set(range);
|
||||
} else
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("will split.\n"));
|
||||
} else {
|
||||
for (Uint32 i = 0; i < 6; i++) // FIX
|
||||
if (!neighborColors.test(i)) {
|
||||
fprintf(stdout, "\twill color %d as %d\n", range, i);
|
||||
color[range] = RegisterName(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
if (coloringFailed) {
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring failed:\n"));
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\twill spill: "));
|
||||
spill.printPretty(UT_LOG_MODULE(RegAlloc));
|
||||
} else {
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring succeeded:\n"));
|
||||
for (Uint32 i = 1; i < rangeCount; i++)
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\trange %d colored as %d\n", i, color[i]));
|
||||
}
|
||||
#endif
|
||||
|
||||
return !coloringFailed;
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
RegisterName* Coloring<RegisterPressure>::simplify(RegisterAllocator& registerAllocator, RegisterName* coloringStack)
|
||||
{
|
||||
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
|
||||
SpillCost* spillCost = registerAllocator.spillCost;
|
||||
Uint32 rangeCount = registerAllocator.rangeCount;
|
||||
|
||||
Uint32* degree = new Uint32[rangeCount];
|
||||
for (RegisterName i = RegisterName(1); i < rangeCount; i = RegisterName(i + 1)) {
|
||||
InterferenceVector* vector = iGraph.getInterferenceVector(i);
|
||||
degree[i] = (vector != NULL) ? vector->count : 0;
|
||||
}
|
||||
|
||||
Pool& pool = registerAllocator.pool;
|
||||
SparseSet low(pool, rangeCount);
|
||||
SparseSet high(pool, rangeCount);
|
||||
SparseSet highInfinite(pool, rangeCount);
|
||||
SparseSet preColored(pool, rangeCount);
|
||||
|
||||
// Get the precolored registers.
|
||||
//
|
||||
VirtualRegisterManager& vrManager = registerAllocator.vrManager;
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
PreColoredRegister* machineEnd = vrManager.getMachineRegistersEnd();
|
||||
for (PreColoredRegister* machinePtr = vrManager.getMachineRegistersBegin(); machinePtr < machineEnd; machinePtr++)
|
||||
if (machinePtr->id != invalidID)
|
||||
preColored.set(name2range[getName(machinePtr->id)]);
|
||||
|
||||
// Insert the live ranges in the sets.
|
||||
//
|
||||
for (Uint32 range = 1; range < rangeCount; range++)
|
||||
if (!preColored.test(range))
|
||||
if (degree[range] < 6) // FIX
|
||||
low.set(range);
|
||||
else if (!spillCost[range].infinite)
|
||||
high.set(range);
|
||||
else
|
||||
highInfinite.set(range);
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring sets:\n\tlow = "));
|
||||
low.printPretty(UT_LOG_MODULE(RegAlloc));
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\thigh = "));
|
||||
high.printPretty(UT_LOG_MODULE(RegAlloc));
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\thighInfinite = "));
|
||||
highInfinite.printPretty(UT_LOG_MODULE(RegAlloc));
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tpreColored = "));
|
||||
preColored.printPretty(UT_LOG_MODULE(RegAlloc));
|
||||
#endif // DEBUG_LOG
|
||||
|
||||
RegisterName* coloringStackPtr = coloringStack;
|
||||
|
||||
while (low.getSize() != 0 || high.getSize() != 0) {
|
||||
while (low.getSize() != 0) {
|
||||
RegisterName range = RegisterName(low.getOne());
|
||||
low.clear(range);
|
||||
*coloringStackPtr++ = range;
|
||||
|
||||
for (InterferenceVector* vector = iGraph.getInterferenceVector(range); vector != NULL; vector = vector->next)
|
||||
for (Int32 i = (vector->count - 1); i >= 0; --i) {
|
||||
RegisterName neighbor = vector->neighbors[i];
|
||||
degree[neighbor]--;
|
||||
|
||||
if (degree[neighbor] < 6) // FIX
|
||||
if (high.test(neighbor)) {
|
||||
high.clear(neighbor);
|
||||
low.set(neighbor);
|
||||
} else if (highInfinite.test(neighbor)) {
|
||||
highInfinite.clear(neighbor);
|
||||
low.set(neighbor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (high.getSize() != 0) {
|
||||
RegisterName best = RegisterName(high.getOne());
|
||||
double bestCost = spillCost[best].cost;
|
||||
double bestDegree = degree[best];
|
||||
|
||||
// Choose the next best candidate.
|
||||
//
|
||||
for (SparseSet::iterator i = high.begin(); !high.done(i); i = high.advance(i)) {
|
||||
RegisterName range = RegisterName(high.get(i));
|
||||
double thisCost = spillCost[range].cost;
|
||||
double thisDegree = degree[range];
|
||||
|
||||
if (thisCost * bestDegree < bestCost * thisDegree) {
|
||||
best = range;
|
||||
bestCost = thisCost;
|
||||
bestDegree = thisDegree;
|
||||
}
|
||||
}
|
||||
|
||||
high.clear(best);
|
||||
low.set(best);
|
||||
}
|
||||
}
|
||||
assert(highInfinite.getSize() == 0);
|
||||
|
||||
delete degree;
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("Coloring stack:\n\t"));
|
||||
for (RegisterName* sp = coloringStack; sp < coloringStackPtr; ++sp)
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("%d ", *sp));
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\n"));
|
||||
#endif // DEBUG_LOG
|
||||
|
||||
return coloringStackPtr;
|
||||
}
|
||||
|
||||
|
||||
template <class RegisterPressure>
|
||||
bool Coloring<RegisterPressure>::color(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
RegisterName* coloringStack = new RegisterName[registerAllocator.rangeCount];
|
||||
return select(registerAllocator, coloringStack, simplify(registerAllocator, coloringStack));
|
||||
}
|
||||
212
mozilla/ef/Compiler/RegisterAllocator/DominatorGraph.cpp
Normal file
212
mozilla/ef/Compiler/RegisterAllocator/DominatorGraph.cpp
Normal file
@@ -0,0 +1,212 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include <string.h>
|
||||
#include "ControlGraph.h"
|
||||
#include "ControlNodes.h"
|
||||
|
||||
#include "DominatorGraph.h"
|
||||
|
||||
DominatorGraph::DominatorGraph(ControlGraph& controlGraph) : controlGraph(controlGraph)
|
||||
{
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
GtoV = new Uint32[nNodes + 1];
|
||||
VtoG = new Uint32[nNodes + 1];
|
||||
|
||||
Uint32 v = 1;
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
VtoG[v] = n;
|
||||
GtoV[n] = v++;
|
||||
}
|
||||
|
||||
// Initialize all the 1-based arrays.
|
||||
//
|
||||
parent = new Uint32[v];
|
||||
semi = new Uint32[v];
|
||||
vertex = new Uint32[v];
|
||||
label = new Uint32[v];
|
||||
size = new Uint32[v];
|
||||
ancestor = new Uint32[v];
|
||||
child = new Uint32[v];
|
||||
dom = new Uint32[v];
|
||||
bucket = new DGLinkedList*[v];
|
||||
|
||||
memset(semi, '\0', v * sizeof(Uint32));
|
||||
memset(bucket, '\0', v * sizeof(DGLinkedList*));
|
||||
|
||||
vCount = v;
|
||||
|
||||
build();
|
||||
|
||||
delete parent;
|
||||
delete semi;
|
||||
delete vertex;
|
||||
delete label;
|
||||
delete size;
|
||||
delete ancestor;
|
||||
delete child;
|
||||
delete dom;
|
||||
delete bucket;
|
||||
}
|
||||
|
||||
Uint32 DominatorGraph::DFS(Uint32 vx, Uint32 n)
|
||||
{
|
||||
semi[vx] = ++n;
|
||||
vertex[n] = label[vx] = vx;
|
||||
ancestor[vx] = child[vx] = 0;
|
||||
size[vx] = 1;
|
||||
|
||||
|
||||
ControlNode& node = *controlGraph.dfsList[VtoG[vx]];
|
||||
ControlEdge* successorEnd = node.getSuccessorsEnd();
|
||||
for (ControlEdge* successorPtr = node.getSuccessorsBegin(); successorPtr < successorEnd; successorPtr++) {
|
||||
Uint32 w = GtoV[successorPtr->getTarget().dfsNum];
|
||||
if (semi[w] == 0) {
|
||||
parent[w] = vx;
|
||||
n = DFS(w, n);
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
void DominatorGraph::LINK(Uint32 vx, Uint32 w)
|
||||
{
|
||||
Uint32 s = w;
|
||||
|
||||
while (semi[label[w]] < semi[label[child[s]]]) {
|
||||
if (size[s] + size[child[child[s]]] >= (size[child[s]] << 1)) {
|
||||
ancestor[child[s]] = s;
|
||||
child[s] = child[child[s]];
|
||||
} else {
|
||||
size[child[s]] = size[s];
|
||||
s = ancestor[s] = child[s];
|
||||
}
|
||||
}
|
||||
label[s] = label[w];
|
||||
size[vx] += size[w];
|
||||
if(size[vx] < (size[w] << 1)) {
|
||||
Uint32 t = s;
|
||||
s = child[vx];
|
||||
child[vx] = t;
|
||||
}
|
||||
while( s != 0 ) {
|
||||
ancestor[s] = vx;
|
||||
s = child[s];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void DominatorGraph::COMPRESS(Uint32 vx)
|
||||
{
|
||||
if(ancestor[ancestor[vx]] != 0) {
|
||||
COMPRESS(ancestor[vx]);
|
||||
if(semi[label[ancestor[vx]]] < semi[label[vx]])
|
||||
label[vx] = label[ancestor[vx]];
|
||||
ancestor[vx] = ancestor[ancestor[vx]];
|
||||
}
|
||||
}
|
||||
|
||||
Uint32 DominatorGraph::EVAL(Uint32 vx)
|
||||
{
|
||||
if(ancestor[vx] == 0)
|
||||
return label[vx];
|
||||
COMPRESS(vx);
|
||||
return (semi[label[ancestor[vx]]] >= semi[label[vx]]) ? label[vx] : label[ancestor[vx]];
|
||||
}
|
||||
|
||||
void DominatorGraph::build()
|
||||
{
|
||||
Uint32 n = DFS(GtoV[0], 0);
|
||||
size[0] = label[0] = semi[0];
|
||||
|
||||
for (Uint32 i = n; i >= 2; i--) {
|
||||
Uint32 w = vertex[i];
|
||||
|
||||
ControlNode& node = *controlGraph.dfsList[VtoG[w]];
|
||||
const DoublyLinkedList<ControlEdge>& predecessors = node.getPredecessors();
|
||||
for (DoublyLinkedList<ControlEdge>::iterator p = predecessors.begin(); !predecessors.done(p); p = predecessors.advance(p)) {
|
||||
Uint32 vx = GtoV[predecessors.get(p).getSource().dfsNum];
|
||||
Uint32 u = EVAL(vx);
|
||||
|
||||
if(semi[u] < semi[w])
|
||||
semi[w] = semi[u];
|
||||
}
|
||||
|
||||
DGLinkedList* elem = new DGLinkedList();
|
||||
elem->next = bucket[vertex[semi[w]]];
|
||||
elem->index = w;
|
||||
bucket[vertex[semi[w]]] = elem;
|
||||
|
||||
LINK(parent[w], w);
|
||||
|
||||
elem = bucket[parent[w]];
|
||||
while(elem != NULL) {
|
||||
Uint32 vx = elem->index;
|
||||
Uint32 u = EVAL(vx);
|
||||
dom[vx] = (semi[u] < semi[vx]) ? u : parent[w];
|
||||
elem = elem->next;
|
||||
}
|
||||
}
|
||||
|
||||
memset(size, '\0', n * sizeof(Uint32));
|
||||
Pool& pool = controlGraph.pool;
|
||||
nodes = new(pool) DGNode[n];
|
||||
|
||||
for(Uint32 j = 2; j <= n; j++) {
|
||||
Uint32 w = vertex[j];
|
||||
Uint32 d = dom[w];
|
||||
if(d != vertex[semi[w]]) {
|
||||
d = dom[d];
|
||||
dom[w] = d;
|
||||
}
|
||||
size[d]++;
|
||||
}
|
||||
dom[GtoV[0]] = 0;
|
||||
|
||||
for (Uint32 k = 1; k <= n; k++) {
|
||||
DGNode& node = nodes[VtoG[k]];
|
||||
Uint32 count = size[k];
|
||||
node.successorsEnd = node.successorsBegin = (count) ? new(pool) Uint32[count] : (Uint32*) 0;
|
||||
}
|
||||
|
||||
for (Uint32 l = 2; l <= n; l++)
|
||||
*(nodes[VtoG[dom[l]]].successorsEnd)++ = VtoG[l];
|
||||
}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
void DominatorGraph::printPretty(LogModuleObject log)
|
||||
{
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Dominator Graph:\n"));
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
for (Uint32 i = 0; i < nNodes; i++) {
|
||||
DGNode& node = nodes[i];
|
||||
if (node.successorsBegin != node.successorsEnd) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\tN%d dominates ", i));
|
||||
for (Uint32* successorsPtr = node.successorsBegin; successorsPtr < node.successorsEnd; successorsPtr++)
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("N%d ", *successorsPtr));
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // DEBUG_LOG
|
||||
|
||||
|
||||
|
||||
80
mozilla/ef/Compiler/RegisterAllocator/DominatorGraph.h
Normal file
80
mozilla/ef/Compiler/RegisterAllocator/DominatorGraph.h
Normal file
@@ -0,0 +1,80 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _DOMINATOR_GRAPH_H_
|
||||
#define _DOMINATOR_GRAPH_H_
|
||||
|
||||
#include "LogModule.h"
|
||||
|
||||
class ControlGraph;
|
||||
|
||||
struct DGNode
|
||||
{
|
||||
Uint32* successorsBegin;
|
||||
Uint32* successorsEnd;
|
||||
};
|
||||
|
||||
struct DGLinkedList
|
||||
{
|
||||
DGLinkedList* next;
|
||||
Uint32 index;
|
||||
};
|
||||
|
||||
class DominatorGraph
|
||||
{
|
||||
private:
|
||||
|
||||
ControlGraph& controlGraph;
|
||||
|
||||
Uint32 vCount;
|
||||
|
||||
Uint32* VtoG;
|
||||
Uint32* GtoV;
|
||||
Uint32* parent;
|
||||
Uint32* semi;
|
||||
Uint32* vertex;
|
||||
Uint32* label;
|
||||
Uint32* size;
|
||||
Uint32* ancestor;
|
||||
Uint32* child;
|
||||
Uint32* dom;
|
||||
DGLinkedList** bucket;
|
||||
DGNode* nodes;
|
||||
|
||||
private:
|
||||
|
||||
void build();
|
||||
|
||||
Uint32 DFS(Uint32 vx, Uint32 n);
|
||||
void LINK(Uint32 vx, Uint32 w);
|
||||
void COMPRESS(Uint32 vx);
|
||||
Uint32 EVAL(Uint32 vx);
|
||||
|
||||
public:
|
||||
|
||||
DominatorGraph(ControlGraph& controlGraph);
|
||||
|
||||
Uint32* getSuccessorsBegin(Uint32 n) const {return nodes[n].successorsBegin;}
|
||||
Uint32* getSuccessorsEnd(Uint32 n) const {return nodes[n].successorsEnd;}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
void printPretty(LogModuleObject log);
|
||||
#endif // DEBUG_LOG
|
||||
};
|
||||
|
||||
#endif // _DOMINATOR_GRAPH_H_
|
||||
20
mozilla/ef/Compiler/RegisterAllocator/HashSet.cpp
Normal file
20
mozilla/ef/Compiler/RegisterAllocator/HashSet.cpp
Normal file
@@ -0,0 +1,20 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "HashSet.h"
|
||||
97
mozilla/ef/Compiler/RegisterAllocator/HashSet.h
Normal file
97
mozilla/ef/Compiler/RegisterAllocator/HashSet.h
Normal file
@@ -0,0 +1,97 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _HASH_SET_H_
|
||||
#define _HASH_SET_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "Pool.h"
|
||||
#include <string.h>
|
||||
|
||||
struct HashSetElement
|
||||
{
|
||||
Uint32 index;
|
||||
HashSetElement* next;
|
||||
};
|
||||
|
||||
class HashSet
|
||||
{
|
||||
private:
|
||||
|
||||
static const hashSize = 64;
|
||||
|
||||
// Return the hash code for the given element index.
|
||||
static Uint32 getHashCode(Uint32 index) {return index & (hashSize - 1);} // Could be better !
|
||||
|
||||
private:
|
||||
|
||||
Pool& allocationPool;
|
||||
HashSetElement** bucket;
|
||||
HashSetElement* free;
|
||||
|
||||
private:
|
||||
|
||||
// No copy constructor.
|
||||
HashSet(const HashSet&);
|
||||
// No copy operator.
|
||||
void operator = (const HashSet&);
|
||||
|
||||
public:
|
||||
|
||||
// Create a new HashSet.
|
||||
inline HashSet(Pool& pool, Uint32 universeSize);
|
||||
|
||||
// Clear the hashset.
|
||||
void clear();
|
||||
// Clear the element for the given index.
|
||||
void clear(Uint32 index);
|
||||
// Set the element for the given index.
|
||||
void set(Uint32 index);
|
||||
// Return true if the element at index is a member.
|
||||
bool test(Uint32 index) const;
|
||||
// Union with the given hashset.
|
||||
inline void or(const HashSet& set);
|
||||
// Intersection with the given hashset.
|
||||
inline void and(const HashSet& set);
|
||||
// Difference with the given hashset.
|
||||
inline void difference(const HashSet& set);
|
||||
|
||||
// Logical operators.
|
||||
HashSet& operator |= (const HashSet& set) {or(set); return *this;}
|
||||
HashSet& operator &= (const HashSet& set) {and(set); return *this;}
|
||||
HashSet& operator -= (const HashSet& set) {difference(set); return *this;}
|
||||
|
||||
// Iterator to conform with the set API.
|
||||
typedef HashSetElement* iterator;
|
||||
// Return the iterator for the first element of this set.
|
||||
iterator begin() const;
|
||||
// Return the next iterator.
|
||||
iterator advance(iterator pos) const;
|
||||
// Return true if the iterator is at the end of the set.
|
||||
bool done(iterator pos) const {return pos == NULL;}
|
||||
};
|
||||
|
||||
|
||||
inline HashSet::HashSet(Pool& pool, Uint32 /*universeSize*/)
|
||||
: allocationPool(pool), free(NULL)
|
||||
{
|
||||
bucket = new(pool) HashSetElement*[hashSize];
|
||||
memset(bucket, '\0', sizeof(HashSetElement*));
|
||||
}
|
||||
|
||||
#endif // _HASH_SET_H_
|
||||
213
mozilla/ef/Compiler/RegisterAllocator/IndexedPool.h
Normal file
213
mozilla/ef/Compiler/RegisterAllocator/IndexedPool.h
Normal file
@@ -0,0 +1,213 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _INDEXED_POOL_H_
|
||||
#define _INDEXED_POOL_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// IndexedPool<IndexedObjectSubclass> is an indexed pool of objects. The
|
||||
// template parameter 'IndexedObjectSubclass' must be a subclass of the struct
|
||||
// IndexedObject.
|
||||
//
|
||||
// When the indexed pool is ask to allocate and initialize a new object (using
|
||||
// the operator new(anIndexedPool) it will zero the memory used to store the
|
||||
// object and initialize the field 'index' of this object to its position in
|
||||
// the pool.
|
||||
//
|
||||
// An object allocated by the indexed pool can be freed by calling the method
|
||||
// IndexedPool::release(IndexedElement& objectIndex).
|
||||
//
|
||||
// example:
|
||||
//
|
||||
// IndexedPool<IndexedElement> elementPool;
|
||||
//
|
||||
// IndexedElement& element1 = *new(elementPool) IndexedElement();
|
||||
// IndexedElement& element2 = *new(elementPool) IndexedElement();
|
||||
//
|
||||
// indexedPool.release(element1);
|
||||
// IndexedElement& element3 = *new(elementPool) IndexedElement();
|
||||
//
|
||||
// At this point element1 is no longer a valid object, element2 is at
|
||||
// index 2 and element3 is at index 1.
|
||||
//
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// IndexedObject -
|
||||
//
|
||||
|
||||
template<class Object>
|
||||
struct IndexedObject
|
||||
{
|
||||
Uint32 index; // Index in the pool.
|
||||
Object* next; // Used to link IndexedObject together.
|
||||
|
||||
Uint32 getIndex() {return index;}
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// IndexedPool<IndexedObject> -
|
||||
//
|
||||
|
||||
template <class IndexedObject>
|
||||
class IndexedPool
|
||||
{
|
||||
private:
|
||||
|
||||
static const blockSize = 4; // Size of one block.
|
||||
|
||||
Uint32 nBlocks; // Number of blocks in the pool.
|
||||
IndexedObject** block; // Array of block pointers.
|
||||
IndexedObject* freeObjects; // Chained list of free IndexedObjects.
|
||||
Uint32 nextIndex; // Index of the next free object in the last block.
|
||||
|
||||
private:
|
||||
|
||||
void allocateAnotherBlock();
|
||||
IndexedObject& newObject();
|
||||
|
||||
public:
|
||||
|
||||
IndexedPool() : nBlocks(0), block(NULL), freeObjects(NULL), nextIndex(1) {}
|
||||
~IndexedPool();
|
||||
|
||||
IndexedObject& get(Uint32 index) const;
|
||||
void release(IndexedObject& object);
|
||||
|
||||
void setSize(Uint32 size) {assert(size < nextIndex); nextIndex = size;}
|
||||
|
||||
// Return the universe size.
|
||||
Uint32 getSize() {return nextIndex;}
|
||||
|
||||
friend void* operator new(size_t, IndexedPool<IndexedObject>& pool); // Needs to call newObject().
|
||||
};
|
||||
|
||||
// Free all the memory allocated for this object.
|
||||
//
|
||||
template <class IndexedObject>
|
||||
IndexedPool<IndexedObject>::~IndexedPool()
|
||||
{
|
||||
for (Uint32 n = 0; n < nBlocks; n++)
|
||||
free(&((IndexedObject **) &block[n][n*blockSize])[-(n + 1)]);
|
||||
}
|
||||
|
||||
// Release the given. This object will be iserted in the chained
|
||||
// list of free IndexedObjects. To minimize the fragmentation the chained list
|
||||
// is ordered by ascending indexes.
|
||||
//
|
||||
template <class IndexedObject>
|
||||
void IndexedPool<IndexedObject>::release(IndexedObject& object)
|
||||
{
|
||||
Uint32 index = object.index;
|
||||
IndexedObject* list = freeObjects;
|
||||
|
||||
assert(&object == &get(index)); // Make sure that object is owned by this pool.
|
||||
|
||||
if (list == NULL) { // The list is empty.
|
||||
freeObjects = &object;
|
||||
object.next = NULL;
|
||||
} else { // The list contains at least 1 element.
|
||||
if (index < list->index) { // insert as first element.
|
||||
freeObjects = &object;
|
||||
object.next = list;
|
||||
} else { // Find this object's place.
|
||||
while ((list->next) != NULL && (list->next->index < index))
|
||||
list = list->next;
|
||||
|
||||
object.next = list->next;
|
||||
list->next = &object;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG
|
||||
// Sanity check to be sure that the list is correctly ordered.
|
||||
for (IndexedObject* obj = freeObjects; obj != NULL; obj = obj->next)
|
||||
if (obj->next != NULL)
|
||||
assert(obj->index < obj->next->index);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Create a new block of IndexedObjects. We will allocate the memory to
|
||||
// store IndexedPool::blockSize IndexedObject and the new Array of block
|
||||
// pointers.
|
||||
// The newly created IndexedObjects will not be initialized.
|
||||
//
|
||||
template <class IndexedObject>
|
||||
void IndexedPool<IndexedObject>::allocateAnotherBlock()
|
||||
{
|
||||
void* memory = (void *) malloc((nBlocks + 1) * sizeof(Uint32) + blockSize * sizeof(IndexedObject));
|
||||
|
||||
memcpy(memory, block, nBlocks * sizeof(Uint32));
|
||||
|
||||
block = (IndexedObject **) memory;
|
||||
IndexedObject* objects = (IndexedObject *) &block[nBlocks + 1];
|
||||
|
||||
block[nBlocks] = &objects[-(nBlocks * blockSize)];
|
||||
nBlocks++;
|
||||
}
|
||||
|
||||
// Return the IndexedObject at the position 'index' in the pool.
|
||||
//
|
||||
template <class IndexedObject>
|
||||
IndexedObject& IndexedPool<IndexedObject>::get(Uint32 index) const
|
||||
{
|
||||
Uint32 blockIndex = index / blockSize;
|
||||
assert(blockIndex < nBlocks);
|
||||
|
||||
return block[blockIndex][index];
|
||||
}
|
||||
|
||||
// Return the reference of an unused object in the pool.
|
||||
//
|
||||
template <class IndexedObject>
|
||||
IndexedObject& IndexedPool<IndexedObject>::newObject()
|
||||
{
|
||||
if (freeObjects != NULL) {
|
||||
IndexedObject& newObject = *freeObjects;
|
||||
freeObjects = newObject.next;
|
||||
return newObject;
|
||||
}
|
||||
|
||||
Uint32 nextIndex = this->nextIndex++;
|
||||
Uint32 blockIndex = nextIndex / blockSize;
|
||||
|
||||
while (blockIndex >= nBlocks)
|
||||
allocateAnotherBlock();
|
||||
|
||||
IndexedObject& newObject = block[blockIndex][nextIndex];
|
||||
newObject.index = nextIndex;
|
||||
|
||||
return newObject;
|
||||
}
|
||||
|
||||
// Return the address of the next unsused object in the given
|
||||
// indexed pool. The field index of the newly allocated object
|
||||
// will be initialized to the corresponding index of this object
|
||||
// in the pool.
|
||||
//
|
||||
template <class IndexedObject>
|
||||
void* operator new(size_t size, IndexedPool<IndexedObject>& pool)
|
||||
{
|
||||
assert(size == sizeof(IndexedObject));
|
||||
return (void *) &pool.newObject();
|
||||
}
|
||||
|
||||
#endif // _INDEXED_POOL_H_
|
||||
258
mozilla/ef/Compiler/RegisterAllocator/InterferenceGraph.h
Normal file
258
mozilla/ef/Compiler/RegisterAllocator/InterferenceGraph.h
Normal file
@@ -0,0 +1,258 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _INTERFERENCE_GRAPH_H_
|
||||
#define _INTERFERENCE_GRAPH_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "Primitives.h"
|
||||
#include "Instruction.h"
|
||||
#include "VirtualRegister.h"
|
||||
#include "RegisterPressure.h"
|
||||
#include "SparseSet.h"
|
||||
#include <string.h>
|
||||
|
||||
struct InterferenceVector
|
||||
{
|
||||
Uint32 count;
|
||||
InterferenceVector* next;
|
||||
RegisterName* neighbors;
|
||||
|
||||
InterferenceVector() : count(0), next(NULL) {}
|
||||
};
|
||||
|
||||
class RegisterAllocator;
|
||||
|
||||
template <class RegisterPressure>
|
||||
class InterferenceGraph
|
||||
{
|
||||
private:
|
||||
|
||||
RegisterAllocator& registerAllocator;
|
||||
|
||||
RegisterPressure::Set* interferences;
|
||||
InterferenceVector** vector;
|
||||
Uint32* offset;
|
||||
Uint32 rangeCount;
|
||||
|
||||
private:
|
||||
|
||||
// No copy constructor.
|
||||
InterferenceGraph(const InterferenceGraph&);
|
||||
// No copy operator.
|
||||
void operator = (const InterferenceGraph&);
|
||||
|
||||
// Check if reg is a member of the universe.
|
||||
void checkMember(RegisterName name) {assert(name < rangeCount);}
|
||||
// Return the edge index for the interference between name1 and name2.
|
||||
Uint32 getEdgeIndex(RegisterName name1, RegisterName name2);
|
||||
|
||||
public:
|
||||
InterferenceGraph(RegisterAllocator& registerAllocator) : registerAllocator(registerAllocator) {}
|
||||
|
||||
// Calculate the interferences.
|
||||
void build();
|
||||
// Return true if reg1 and reg2 interfere.
|
||||
bool interfere(RegisterName name1, RegisterName name2);
|
||||
// Return the interference vector for the given register or NULL if there is none.
|
||||
InterferenceVector* getInterferenceVector(RegisterName name) {return vector[name];}
|
||||
// Set the interference between name1 and name2.
|
||||
void setInterference(RegisterName name1, RegisterName name2);
|
||||
// Set the interference vector for the given register.
|
||||
void setInterferenceVector(RegisterName name, InterferenceVector* v) {vector[name] = v;}
|
||||
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
// Print the interferences.
|
||||
void printPretty(LogModuleObject log);
|
||||
#endif // DEBUG_LOG
|
||||
};
|
||||
|
||||
template <class RegisterPressure>
|
||||
void InterferenceGraph<RegisterPressure>::build()
|
||||
{
|
||||
Pool& pool = registerAllocator.pool;
|
||||
Uint32 rangeCount = registerAllocator.rangeCount;
|
||||
this->rangeCount = rangeCount;
|
||||
|
||||
// Initialize the structures.
|
||||
//
|
||||
offset = new(pool) Uint32[rangeCount + 1];
|
||||
vector = new(pool) InterferenceVector*[rangeCount];
|
||||
memset(vector, '\0', sizeof(InterferenceVector*) * rangeCount);
|
||||
|
||||
Uint32 o = 0;
|
||||
offset[0] = 0;
|
||||
for (Uint32 i = 1; i <= rangeCount; ++i) {
|
||||
offset[i] = o;
|
||||
o += i;
|
||||
}
|
||||
|
||||
interferences = new(pool) RegisterPressure::Set(pool, (rangeCount * rangeCount) / 2);
|
||||
|
||||
ControlGraph& controlGraph = registerAllocator.controlGraph;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
LivenessInfo<RegisterPressure> liveness = Liveness<RegisterPressure>::analysis(controlGraph, rangeCount, name2range);
|
||||
registerAllocator.liveness = liveness;
|
||||
SparseSet currentLive(pool, rangeCount);
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
ControlNode& node = *nodes[n];
|
||||
currentLive = liveness.liveOut[n];
|
||||
|
||||
InstructionList& instructions = node.getInstructions();
|
||||
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
InstructionUse* useBegin = instruction.getInstructionUseBegin();
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
InstructionUse* usePtr;
|
||||
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
InstructionDefine* definePtr;
|
||||
|
||||
// Handle the copy instruction to avoid unnecessary interference between the 2 registers.
|
||||
if ((instruction.getFlags() & ifCopy) != 0) {
|
||||
assert(useBegin != useEnd && useBegin[0].isRegister());
|
||||
currentLive.clear(name2range[useBegin[0].getRegisterName()]);
|
||||
}
|
||||
|
||||
// Create the interferences.
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister()) {
|
||||
RegisterName define = name2range[definePtr->getRegisterName()];
|
||||
|
||||
for (SparseSet::iterator e = currentLive.begin(); !currentLive.done(e); e = currentLive.advance(e)) {
|
||||
RegisterName live = RegisterName(currentLive.get(e));
|
||||
|
||||
if ((live != define) && !interfere(live, define) && registerAllocator.canInterfere(live, define)) {
|
||||
|
||||
if (vector[define] == NULL)
|
||||
vector[define] = new(pool) InterferenceVector();
|
||||
vector[define]->count++;
|
||||
|
||||
if (vector[live] == NULL)
|
||||
vector[live] = new(pool) InterferenceVector();
|
||||
vector[live]->count++;
|
||||
|
||||
setInterference(live, define);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Now update the liveness.
|
||||
//
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
currentLive.clear(name2range[definePtr->getRegisterName()]);
|
||||
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister())
|
||||
currentLive.set(name2range[usePtr->getRegisterName()]);
|
||||
}
|
||||
}
|
||||
|
||||
// Allocate the memory to store the interferences.
|
||||
//
|
||||
for (Uint32 e = 0; e < rangeCount; e++)
|
||||
if (vector[e] != NULL) {
|
||||
InterferenceVector& v = *vector[e];
|
||||
v.neighbors = new(pool) RegisterName[v.count];
|
||||
v.count = 0;
|
||||
}
|
||||
|
||||
// Initialize the edges.
|
||||
//
|
||||
if (RegisterPressure::Set::isOrdered()) {
|
||||
RegisterName name1 = RegisterName(0);
|
||||
|
||||
for (RegisterPressure::Set::iterator i = interferences->begin(); !interferences->done(i); i = interferences->advance(i)) {
|
||||
Uint32 interferenceIndex = interferences->get(i);
|
||||
|
||||
while(interferenceIndex >= offset[name1 + 1])
|
||||
name1 = RegisterName(name1 + 1);
|
||||
|
||||
assert((interferenceIndex >= offset[name1]) && (interferenceIndex < offset[name1 + 1]));
|
||||
|
||||
RegisterName name2 = RegisterName(interferenceIndex - offset[name1]);
|
||||
|
||||
assert(interfere(name1, name2));
|
||||
|
||||
InterferenceVector& vector1 = *vector[name1];
|
||||
vector1.neighbors[vector1.count++] = name2;
|
||||
|
||||
InterferenceVector& vector2 = *vector[name2];
|
||||
vector2.neighbors[vector2.count++] = name1;
|
||||
}
|
||||
} else {
|
||||
trespass("not Implemented"); // FIX: need one more pass to initialize the vectors.
|
||||
}
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
Uint32 InterferenceGraph<RegisterPressure>::getEdgeIndex(RegisterName name1, RegisterName name2)
|
||||
{
|
||||
checkMember(name1); checkMember(name2);
|
||||
assert(name1 != name2); // This is not possible.
|
||||
return (name1 < name2) ? offset[name2] + name1 : offset[name1] + name2;
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
void InterferenceGraph<RegisterPressure>::setInterference(RegisterName name1, RegisterName name2)
|
||||
{
|
||||
interferences->set(getEdgeIndex(name1, name2));
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
bool InterferenceGraph<RegisterPressure>::interfere(RegisterName name1, RegisterName name2)
|
||||
{
|
||||
return interferences->test(getEdgeIndex(name1, name2));
|
||||
}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
template <class RegisterPressure>
|
||||
void InterferenceGraph<RegisterPressure>::printPretty(LogModuleObject log)
|
||||
{
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Interference Vectors:\n"));
|
||||
for (Uint32 i = 1; i < rangeCount; i++) {
|
||||
if (vector[i] != NULL) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\tvr%d: (", i));
|
||||
for (InterferenceVector* v = vector[i]; v != NULL; v = v->next)
|
||||
for (Uint32 j = 0; j < v->count; j++) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%d", v->neighbors[j]));
|
||||
if (v->next != NULL || j != (v->count - 1))
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (","));
|
||||
}
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (")\n"));
|
||||
}
|
||||
}
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Interference Matrix:\n"));
|
||||
for (RegisterName name1 = RegisterName(1); name1 < rangeCount; name1 = RegisterName(name1 + 1)) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\t%d:\t", name1));
|
||||
for (RegisterName name2 = RegisterName(1); name2 < rangeCount; name2 = RegisterName(name2 + 1))
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%c", ((name1 != name2) && interfere(name1, name2)) ? '1' : '0'));
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
|
||||
}
|
||||
}
|
||||
#endif // DEBUG_LOG
|
||||
|
||||
#endif // _INTERFERENCE_GRAPH_H_
|
||||
87
mozilla/ef/Compiler/RegisterAllocator/LiveRange.h
Normal file
87
mozilla/ef/Compiler/RegisterAllocator/LiveRange.h
Normal file
@@ -0,0 +1,87 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _LIVE_RANGE_H_
|
||||
#define _LIVE_RANGE_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "ControlNodes.h"
|
||||
#include "Primitives.h"
|
||||
#include "Instruction.h"
|
||||
#include "RegisterAllocator.h"
|
||||
#include "RegisterAllocatorTools.h"
|
||||
|
||||
template <class RegisterPressure>
|
||||
struct LiveRange
|
||||
{
|
||||
static void build(RegisterAllocator& registerAllocator);
|
||||
};
|
||||
|
||||
template <class RegisterPressure>
|
||||
void LiveRange<RegisterPressure>::build(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
// Intialize the lookup table.
|
||||
//
|
||||
Uint32 nameCount = registerAllocator.nameCount;
|
||||
RegisterName* nameTable = new(registerAllocator.pool) RegisterName[2*nameCount];
|
||||
RegisterName* rangeName = &nameTable[nameCount];
|
||||
|
||||
init(rangeName, nameCount);
|
||||
|
||||
// Walk the graph.
|
||||
//
|
||||
ControlGraph& controlGraph = registerAllocator.controlGraph;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
SparseSet destination(registerAllocator.pool, nameCount);
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
|
||||
|
||||
destination.clear();
|
||||
for (InstructionList::iterator i = phiNodes.begin(); !phiNodes.done(i); i = phiNodes.advance(i)) {
|
||||
Instruction& phiNode = phiNodes.get(i);
|
||||
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd() && phiNode.getInstructionDefineBegin()[0].isRegister());
|
||||
destination.set(findRoot(phiNode.getInstructionDefineBegin()[0].getRegisterName(), rangeName));
|
||||
}
|
||||
|
||||
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
|
||||
Instruction& phiNode = phiNodes.get(p);
|
||||
|
||||
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd() && phiNode.getInstructionDefineBegin()[0].isRegister());
|
||||
RegisterName destinationName = phiNode.getInstructionDefineBegin()[0].getRegisterName();
|
||||
RegisterName destinationRoot = findRoot(destinationName, rangeName);
|
||||
|
||||
InstructionUse* useEnd = phiNode.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = phiNode.getInstructionUseBegin(); usePtr < useEnd; usePtr++) {
|
||||
assert(usePtr->isRegister());
|
||||
RegisterName sourceName = usePtr->getRegisterName();
|
||||
RegisterName sourceRoot = findRoot(sourceName, rangeName);
|
||||
|
||||
if (sourceRoot != destinationRoot && !destination.test(sourceRoot))
|
||||
rangeName[sourceRoot] = destinationRoot;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAllocator.rangeCount = compress(registerAllocator.name2range, rangeName, nameCount, nameCount);
|
||||
}
|
||||
|
||||
#endif // _LIVE_RANGE_H_
|
||||
163
mozilla/ef/Compiler/RegisterAllocator/LiveRangeGraph.h
Normal file
163
mozilla/ef/Compiler/RegisterAllocator/LiveRangeGraph.h
Normal file
@@ -0,0 +1,163 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _LIVE_RANGE_GRAPH_
|
||||
#define _LIVE_RANGE_GRAPH_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "Pool.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "ControlNodes.h"
|
||||
#include "Instruction.h"
|
||||
#include "RegisterTypes.h"
|
||||
|
||||
class RegisterAllocator;
|
||||
|
||||
template <class RegisterPressure>
|
||||
class LiveRangeGraph
|
||||
{
|
||||
private:
|
||||
|
||||
RegisterAllocator& registerAllocator;
|
||||
|
||||
RegisterPressure::Set* edges;
|
||||
Uint32 rangeCount;
|
||||
|
||||
public:
|
||||
//
|
||||
//
|
||||
LiveRangeGraph(RegisterAllocator& registerAllocator) : registerAllocator(registerAllocator) {}
|
||||
|
||||
//
|
||||
//
|
||||
void build();
|
||||
|
||||
//
|
||||
//
|
||||
void addEdge(RegisterName name1, RegisterName name2);
|
||||
|
||||
//
|
||||
//
|
||||
bool haveEdge(RegisterName name1, RegisterName name2);
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
//
|
||||
//
|
||||
void printPretty(LogModuleObject log);
|
||||
#endif // DEBUG_LOG
|
||||
};
|
||||
|
||||
template <class RegisterPressure>
|
||||
void LiveRangeGraph<RegisterPressure>::build()
|
||||
{
|
||||
Pool& pool = registerAllocator.pool;
|
||||
Uint32 rangeCount = registerAllocator.rangeCount;
|
||||
this->rangeCount = rangeCount;
|
||||
|
||||
edges = new(pool) RegisterPressure::Set(pool, rangeCount * rangeCount);
|
||||
|
||||
ControlGraph& controlGraph = registerAllocator.controlGraph;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
LivenessInfo<RegisterPressure>& liveness = registerAllocator.liveness;
|
||||
SparseSet currentLive(pool, rangeCount);
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
ControlNode& node = *nodes[n];
|
||||
currentLive = liveness.liveOut[n];
|
||||
|
||||
InstructionList& instructions = node.getInstructions();
|
||||
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
InstructionUse* useBegin = instruction.getInstructionUseBegin();
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
InstructionUse* usePtr;
|
||||
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
InstructionDefine* definePtr;
|
||||
|
||||
if ((instruction.getFlags() & ifCopy) != 0) {
|
||||
assert(useBegin != useEnd && useBegin[0].isRegister());
|
||||
currentLive.clear(name2range[useBegin[0].getRegisterName()]);
|
||||
}
|
||||
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister()) {
|
||||
RegisterName define = name2range[definePtr->getRegisterName()];
|
||||
|
||||
for (SparseSet::iterator l = currentLive.begin(); !currentLive.done(l); l = currentLive.advance(l)) {
|
||||
RegisterName live = RegisterName(currentLive.get(l));
|
||||
if (define != live && registerAllocator.canInterfere(define, live))
|
||||
addEdge(define, live);
|
||||
}
|
||||
}
|
||||
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
currentLive.clear(name2range[definePtr->getRegisterName()]);
|
||||
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister())
|
||||
currentLive.set(name2range[usePtr->getRegisterName()]);
|
||||
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
RegisterName use = name2range[usePtr->getRegisterName()];
|
||||
|
||||
for (SparseSet::iterator l = currentLive.begin(); !currentLive.done(l); l = currentLive.advance(l)) {
|
||||
RegisterName live = RegisterName(currentLive.get(l));
|
||||
if (use != live && registerAllocator.canInterfere(use, live))
|
||||
addEdge(use, live);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
void LiveRangeGraph<RegisterPressure>::addEdge(RegisterName name1, RegisterName name2)
|
||||
{
|
||||
assert(name1 != name2);
|
||||
edges->set(name1 * rangeCount + name2);
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
bool LiveRangeGraph<RegisterPressure>::haveEdge(RegisterName name1, RegisterName name2)
|
||||
{
|
||||
assert(name1 != name2);
|
||||
return edges->test(name1 * rangeCount + name2);
|
||||
}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
template <class RegisterPressure>
|
||||
void LiveRangeGraph<RegisterPressure>::printPretty(LogModuleObject log)
|
||||
{
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Live ranges graph:\n"));
|
||||
for (RegisterName name1 = RegisterName(1); name1 < rangeCount; name1 = RegisterName(name1 + 1)) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\t%d:\t", name1));
|
||||
for (RegisterName name2 = RegisterName(1); name2 < rangeCount; name2 = RegisterName(name2 + 1))
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%c", ((name1 != name2) && haveEdge(name1, name2)) ? '1' : '0'));
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
|
||||
}
|
||||
}
|
||||
#endif // DEBUG_LOG
|
||||
|
||||
#endif // _LIVE_RANGE_GRAPH_
|
||||
21
mozilla/ef/Compiler/RegisterAllocator/Liveness.cpp
Normal file
21
mozilla/ef/Compiler/RegisterAllocator/Liveness.cpp
Normal file
@@ -0,0 +1,21 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "Liveness.h"
|
||||
|
||||
301
mozilla/ef/Compiler/RegisterAllocator/Liveness.h
Normal file
301
mozilla/ef/Compiler/RegisterAllocator/Liveness.h
Normal file
@@ -0,0 +1,301 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _LIVENESS_H_
|
||||
#define _LIVENESS_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "ControlNodes.h"
|
||||
#include "Instruction.h"
|
||||
#include "RegisterTypes.h"
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// LivenessInfo -
|
||||
|
||||
template <class RegisterPressure>
|
||||
struct LivenessInfo
|
||||
{
|
||||
RegisterPressure::Set* liveIn;
|
||||
RegisterPressure::Set* liveOut;
|
||||
DEBUG_LOG_ONLY(Uint32 size);
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
void printPretty(LogModuleObject log);
|
||||
#endif // DEBUG_LOG
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Liveness
|
||||
//
|
||||
// The liveness is defined by the following data-flow equations:
|
||||
//
|
||||
// LiveIn(n) = LocalLive(n) U (LiveOut(n) - Killed(n)).
|
||||
// LiveOut(n) = U LiveIn(s) (s a successor of n).
|
||||
//
|
||||
// where LocalLive(n) is the set of used registers in the block n, Killed(n)
|
||||
// is the set of defined registers in the block n, LiveIn(n) is the set of
|
||||
// live registers at the begining of the block n and LiveOut(n) is the set
|
||||
// of live registers at the end of the block n.
|
||||
//
|
||||
//
|
||||
// We will compute the liveness analysis in two stages:
|
||||
//
|
||||
// 1- Build LocalLive(n) (wich is an approximation of LiveIn(n)) and Killed(n)
|
||||
// for each block n.
|
||||
// 2- Perform a backward data-flow analysis to propagate the liveness information
|
||||
// through the entire control-flow graph.
|
||||
//
|
||||
|
||||
template <class RegisterPressure>
|
||||
struct Liveness
|
||||
{
|
||||
static LivenessInfo<RegisterPressure> analysis(ControlGraph& controlGraph, Uint32 rangeCount, const RegisterName* name2range);
|
||||
static LivenessInfo<RegisterPressure> analysis(ControlGraph& controlGraph, Uint32 nameCount);
|
||||
};
|
||||
|
||||
template <class RegisterPressure>
|
||||
LivenessInfo<RegisterPressure> Liveness<RegisterPressure>::analysis(ControlGraph& controlGraph, Uint32 rangeCount, const RegisterName* name2range)
|
||||
{
|
||||
Pool& pool = controlGraph.pool;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
// Allocate the temporary sets.
|
||||
RegisterPressure::Set* killed = new(pool) RegisterPressure::Set[nNodes](pool, rangeCount);
|
||||
|
||||
// Allocate the globals sets.
|
||||
RegisterPressure::Set* liveIn = new(pool) RegisterPressure::Set[nNodes](pool, rangeCount);
|
||||
RegisterPressure::Set* liveOut = new(pool) RegisterPressure::Set[nNodes](pool, rangeCount);
|
||||
|
||||
// First stage of the liveness analysis: Compute the sets LocalLive(stored in LiveIn) and Killed.
|
||||
//
|
||||
for (Uint32 n = 0; n < (nNodes - 1); n++) {
|
||||
ControlNode& node = *nodes[n];
|
||||
|
||||
RegisterPressure::Set& currentLocalLive = liveIn[n];
|
||||
RegisterPressure::Set& currentKilled = killed[n];
|
||||
|
||||
// Find the instructions contributions to the sets LocalLive and Killed.
|
||||
//
|
||||
InstructionList& instructions = node.getInstructions();
|
||||
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
// If a VirtualRegister is 'used' before being 'defined' then we add it to set LocalLive.
|
||||
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
Uint32 index = name2range[usePtr->getRegisterName()];
|
||||
|
||||
if (!currentKilled.test(index))
|
||||
currentLocalLive.set(index);
|
||||
}
|
||||
|
||||
// If a Virtualregister is 'defined' then we add it to the set Killed.
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
currentKilled.set(name2range[definePtr->getRegisterName()]);
|
||||
}
|
||||
}
|
||||
|
||||
// Second stage of the liveness analysis: We propagate the LiveIn & LiveOut through the entire
|
||||
// control-flow graph.
|
||||
//
|
||||
RegisterPressure::Set temp(pool, rangeCount);
|
||||
|
||||
bool changed;
|
||||
do {
|
||||
changed = false;
|
||||
|
||||
// For all nodes is this graph except the endNode.
|
||||
for (Int32 n = (nNodes - 2); n >= 0; n--) {
|
||||
ControlNode& node = *nodes[n];
|
||||
|
||||
RegisterPressure::Set& currentLiveIn = liveIn[n];
|
||||
RegisterPressure::Set& currentLiveOut = liveOut[n];
|
||||
|
||||
// Compute temp = Union of LiveIn(s) (s a successor of this node) | usedByPhiNodes(n).
|
||||
// temp will be the new LiveOut(n).
|
||||
Uint32 nSuccessors = node.nSuccessors();
|
||||
if (nSuccessors != 0) {
|
||||
temp = liveIn[node.nthSuccessor(0).getTarget().dfsNum];
|
||||
for (Uint32 s = 1; s < nSuccessors; s++)
|
||||
temp |= liveIn[node.nthSuccessor(s).getTarget().dfsNum];
|
||||
} else
|
||||
temp.clear();
|
||||
|
||||
// If temp and LiveOut(n) differ then set LiveOut(n) = temp and recalculate the
|
||||
// new LiveIn(n).
|
||||
if (currentLiveOut != temp) {
|
||||
currentLiveOut = temp;
|
||||
temp -= killed[n]; // FIX: could be optimized with one call to unionDiff !
|
||||
temp |= currentLiveIn;
|
||||
|
||||
if (currentLiveIn != temp) {
|
||||
currentLiveIn = temp;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} while(changed);
|
||||
|
||||
LivenessInfo<RegisterPressure> liveness;
|
||||
liveness.liveIn = liveIn;
|
||||
liveness.liveOut = liveOut;
|
||||
DEBUG_LOG_ONLY(liveness.size = nNodes);
|
||||
return liveness;
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
LivenessInfo<RegisterPressure> Liveness<RegisterPressure>::analysis(ControlGraph& controlGraph, Uint32 nameCount)
|
||||
{
|
||||
Pool& pool = controlGraph.pool;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
// Allocate the temporary sets.
|
||||
RegisterPressure::Set* killed = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
|
||||
RegisterPressure::Set* usedByPhiNodes = NULL;
|
||||
|
||||
// Allocate the globals sets.
|
||||
RegisterPressure::Set* liveIn = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
|
||||
RegisterPressure::Set* liveOut = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
|
||||
|
||||
// First stage of the liveness analysis: Compute the sets LocalLive(stored in LiveIn) and Killed.
|
||||
//
|
||||
for (Uint32 n = 0; n < (nNodes - 1); n++) {
|
||||
ControlNode& node = *nodes[n];
|
||||
|
||||
RegisterPressure::Set& currentLocalLive = liveIn[n];
|
||||
RegisterPressure::Set& currentKilled = killed[n];
|
||||
|
||||
InstructionList& phiNodes = node.getPhiNodeInstructions();
|
||||
|
||||
if ((usedByPhiNodes == NULL) && !phiNodes.empty())
|
||||
usedByPhiNodes = new(pool) RegisterPressure::Set[nNodes](pool, nameCount);
|
||||
|
||||
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
|
||||
Instruction& phiNode = phiNodes.get(p);
|
||||
|
||||
InstructionDefine& define = phiNode.getInstructionDefineBegin()[0];
|
||||
currentKilled.set(define.getRegisterName());
|
||||
|
||||
typedef DoublyLinkedList<ControlEdge> ControlEdgeList;
|
||||
const ControlEdgeList& predecessors = node.getPredecessors();
|
||||
ControlEdgeList::iterator p = predecessors.begin();
|
||||
InstructionUse* useEnd = phiNode.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = phiNode.getInstructionUseBegin(); usePtr < useEnd; usePtr++, p = predecessors.advance(p))
|
||||
if (usePtr->isRegister())
|
||||
usedByPhiNodes[predecessors.get(p).getSource().dfsNum].set(usePtr->getRegisterName());
|
||||
}
|
||||
|
||||
// Find the instructions contributions to the sets LocalLive and Killed.
|
||||
//
|
||||
InstructionList& instructions = node.getInstructions();
|
||||
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
// If a VirtualRegister is 'used' before being 'defined' then we add it to set LocalLive.
|
||||
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
Uint32 index = usePtr->getRegisterName();
|
||||
|
||||
if (!currentKilled.test(index))
|
||||
currentLocalLive.set(index);
|
||||
}
|
||||
|
||||
// If a Virtualregister is 'defined' then we add it to the set Killed.
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
currentKilled.set(definePtr->getRegisterName());
|
||||
}
|
||||
}
|
||||
|
||||
// Second stage of the liveness analysis: We propagate the LiveIn & LiveOut through the entire
|
||||
// control-flow graph.
|
||||
//
|
||||
RegisterPressure::Set temp(pool, nameCount);
|
||||
|
||||
bool changed;
|
||||
do {
|
||||
changed = false;
|
||||
|
||||
// For all nodes is this graph except the endNode.
|
||||
for (Int32 n = (nNodes - 2); n >= 0; n--) {
|
||||
ControlNode& node = *nodes[n];
|
||||
|
||||
RegisterPressure::Set& currentLiveIn = liveIn[n];
|
||||
RegisterPressure::Set& currentLiveOut = liveOut[n];
|
||||
|
||||
// Compute temp = Union of LiveIn(s) (s a successor of this node) | usedByPhiNodes(n).
|
||||
// temp will be the new LiveOut(n).
|
||||
Uint32 nSuccessors = node.nSuccessors();
|
||||
if (nSuccessors != 0) {
|
||||
temp = liveIn[node.nthSuccessor(0).getTarget().dfsNum];
|
||||
for (Uint32 s = 1; s < nSuccessors; s++)
|
||||
temp |= liveIn[node.nthSuccessor(s).getTarget().dfsNum];
|
||||
} else
|
||||
temp.clear();
|
||||
|
||||
// Insert the phiNodes contribution.
|
||||
if (usedByPhiNodes != NULL)
|
||||
temp |= usedByPhiNodes[n];
|
||||
|
||||
// If temp and LiveOut(n) differ then set LiveOut(n) = temp and recalculate the
|
||||
// new LiveIn(n).
|
||||
if (currentLiveOut != temp) {
|
||||
currentLiveOut = temp;
|
||||
temp -= killed[n]; // FIX: could be optimized with one call to unionDiff !
|
||||
temp |= currentLiveIn;
|
||||
|
||||
if (currentLiveIn != temp) {
|
||||
currentLiveIn = temp;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} while(changed);
|
||||
|
||||
LivenessInfo<RegisterPressure> liveness;
|
||||
liveness.liveIn = liveIn;
|
||||
liveness.liveOut = liveOut;
|
||||
DEBUG_LOG_ONLY(liveness.size = nNodes);
|
||||
return liveness;
|
||||
}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
template <class RegisterPressure>
|
||||
void LivenessInfo<RegisterPressure>::printPretty(LogModuleObject log)
|
||||
{
|
||||
for (Uint32 n = 0; n < size; n++) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Node N%d:\n\tliveIn = ", n));
|
||||
liveIn[n].printPretty(log);
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\tliveOut = "));
|
||||
liveOut[n].printPretty(log);
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
|
||||
}
|
||||
}
|
||||
#endif // DEBUG_LOG
|
||||
|
||||
#endif // _LIVENESS_H_
|
||||
40
mozilla/ef/Compiler/RegisterAllocator/Makefile
Normal file
40
mozilla/ef/Compiler/RegisterAllocator/Makefile
Normal file
@@ -0,0 +1,40 @@
|
||||
#! gmake
|
||||
|
||||
DEPTH = ../..
|
||||
|
||||
MODULE_NAME = RegisterAllocator
|
||||
|
||||
include $(DEPTH)/config/config.mk
|
||||
|
||||
INCLUDES += \
|
||||
-I$(DEPTH)/Utilities/General \
|
||||
-I$(DEPTH)/Utilities/zlib \
|
||||
-I$(DEPTH)/Runtime/ClassReader \
|
||||
-I$(DEPTH)/Runtime/NativeMethods \
|
||||
-I$(DEPTH)/Runtime/System \
|
||||
-I$(DEPTH)/Runtime/ClassInfo \
|
||||
-I$(DEPTH)/Runtime/FileReader \
|
||||
-I$(DEPTH)/Compiler/PrimitiveGraph \
|
||||
-I$(DEPTH)/Compiler/FrontEnd \
|
||||
-I$(DEPTH)/Compiler/Optimizer \
|
||||
-I$(DEPTH)/Compiler/CodeGenerator \
|
||||
-I$(DEPTH)/Compiler/CodeGenerator/md \
|
||||
-I$(DEPTH)/Compiler/CodeGenerator/md/$(CPU_ARCH) \
|
||||
-I$(DEPTH)/Compiler/RegisterAllocator \
|
||||
-I$(DEPTH)/Driver/StandAloneJava \
|
||||
-I$(DEPTH)/Debugger \
|
||||
$(NULL)
|
||||
|
||||
CXXSRCS = \
|
||||
RegisterAllocator.cpp \
|
||||
RegisterAllocatorTools.cpp \
|
||||
DominatorGraph.cpp \
|
||||
VirtualRegister.cpp \
|
||||
BitSet.cpp \
|
||||
SparseSet.cpp \
|
||||
$(NULL)
|
||||
|
||||
|
||||
include $(DEPTH)/config/rules.mk
|
||||
|
||||
libs:: $(MODULE)
|
||||
392
mozilla/ef/Compiler/RegisterAllocator/PhiNodeRemover.h
Normal file
392
mozilla/ef/Compiler/RegisterAllocator/PhiNodeRemover.h
Normal file
@@ -0,0 +1,392 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _PHI_NODE_REMOVER_H_
|
||||
#define _PHI_NODE_REMOVER_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "Pool.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "DominatorGraph.h"
|
||||
#include "VirtualRegister.h"
|
||||
#include "RegisterPressure.h"
|
||||
#include "Liveness.h"
|
||||
#include "Instruction.h"
|
||||
#include "InstructionEmitter.h"
|
||||
#include "SparseSet.h"
|
||||
#include <string.h>
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// RegisterNameNode -
|
||||
|
||||
struct RegisterNameNode
|
||||
{
|
||||
RegisterNameNode* next;
|
||||
RegisterName newName;
|
||||
Uint32 nextPushed;
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// CopyData -
|
||||
|
||||
struct CopyData
|
||||
{
|
||||
RegisterName source;
|
||||
RegisterClassKind classKind;
|
||||
Uint32 useCount;
|
||||
bool isLiveOut;
|
||||
RegisterName sourceNameToUse;
|
||||
RegisterName temporaryName;
|
||||
RegisterNameNode* newName;
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// PhiNodeRemover<RegisterPressure> -
|
||||
|
||||
template <class RegisterPressure>
|
||||
struct PhiNodeRemover
|
||||
{
|
||||
// Replace the phi nodes by copy instructions.
|
||||
static void replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter);
|
||||
};
|
||||
|
||||
// Split some of the critical edges and return true if there are still some
|
||||
// in the graph after that.
|
||||
//
|
||||
static bool splitCriticalEdges(ControlGraph& /*cg*/)
|
||||
{
|
||||
// FIX: not implemented.
|
||||
return true;
|
||||
}
|
||||
|
||||
inline void pushName(Pool& pool, RegisterNameNode** stack, SparseSet& pushed, Uint32* nodeListPointer, RegisterName oldName, RegisterName newName)
|
||||
{
|
||||
RegisterNameNode& newNode = *new(pool) RegisterNameNode();
|
||||
|
||||
if (pushed.test(oldName))
|
||||
(*stack)->newName = newName;
|
||||
else {
|
||||
newNode.newName = newName;
|
||||
newNode.nextPushed = *nodeListPointer;
|
||||
*nodeListPointer = oldName;
|
||||
newNode.next = *stack;
|
||||
*stack = &newNode;
|
||||
pushed.set(oldName);
|
||||
}
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
void PhiNodeRemover<RegisterPressure>::replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter)
|
||||
{
|
||||
Pool& pool = controlGraph.pool;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
// Initialize the local variables.
|
||||
//
|
||||
|
||||
// When we insert the copies we will also need to create new VirtualRegisters for
|
||||
// the insertion of temporaries. The maximum number of temporary register will not
|
||||
// exceed the number of phiNodes in the primitive graph.
|
||||
Uint32 nameCount = vrManager.getSize();
|
||||
Uint32 maxNameCount = nameCount;
|
||||
for (Uint32 n = 0; n < nNodes; n++)
|
||||
maxNameCount += nodes[n]->getPhiNodes().length();
|
||||
|
||||
// If the CFG contains some critical edges (backward edge which source has more than one
|
||||
// outgoing edge and destination has more than one incomimg edge) then we need the liveness
|
||||
// information to be able to insert temporary copies.
|
||||
RegisterPressure::Set* liveOut = NULL;
|
||||
if (splitCriticalEdges(controlGraph))
|
||||
liveOut = Liveness<LowRegisterPressure>::analysis(controlGraph, nameCount).liveOut;
|
||||
|
||||
DominatorGraph dGraph(controlGraph);
|
||||
|
||||
SparseSet pushed(pool, maxNameCount);
|
||||
SparseSet destinationList(pool, maxNameCount);
|
||||
SparseSet workList(pool, maxNameCount);
|
||||
|
||||
CopyData* copyStats = new(pool) CopyData[maxNameCount];
|
||||
memset(copyStats, '\0', maxNameCount*sizeof(CopyData));
|
||||
|
||||
struct NodeStack {
|
||||
Uint32* next;
|
||||
Uint32* limit;
|
||||
Uint32 pushedList;
|
||||
};
|
||||
|
||||
// Allocate the node stack and initialize the node stack pointer.
|
||||
NodeStack* nodeStack = new(pool) NodeStack[nNodes + 1];
|
||||
NodeStack* nodeStackPtr = nodeStack;
|
||||
|
||||
// We start by the begin node.
|
||||
Uint32 startNode = 0;
|
||||
Uint32* next = &startNode;
|
||||
Uint32* limit = &startNode + 1;
|
||||
|
||||
while (true) {
|
||||
|
||||
if (next == limit) {
|
||||
// If there are no more node in the sibling, we have to pop the current
|
||||
// frame from the stack and update the copyStats of the pushed nodes.
|
||||
//
|
||||
if (nodeStackPtr == nodeStack)
|
||||
// We are at the bottom of the stack and there are no more nodes
|
||||
// to look at. We are done !
|
||||
break;
|
||||
|
||||
--nodeStackPtr;
|
||||
// We are done with all the children of this node in the dominator tree.
|
||||
// We need to update the copy information of all the new names pushed
|
||||
// during the walk over this node.
|
||||
Uint32 pushedList = nodeStackPtr->pushedList;
|
||||
while (pushedList != 0) {
|
||||
Uint32 nextName = copyStats[pushedList].newName->nextPushed;
|
||||
copyStats[pushedList].newName = copyStats[pushedList].newName->next;
|
||||
pushedList = nextName;
|
||||
}
|
||||
|
||||
// restore the previous frame.
|
||||
next = nodeStackPtr->next;
|
||||
limit = nodeStackPtr->limit;
|
||||
} else {
|
||||
Uint32 currentNode = *next++;
|
||||
Uint32 pushedList = 0;
|
||||
|
||||
|
||||
// Initialize the sets.
|
||||
pushed.clear();
|
||||
destinationList.clear();
|
||||
|
||||
// STEP1:
|
||||
// Walk the instruction list and to replace all the instruction uses with their new name.
|
||||
// If the instruction is a phi node and its defined register is alive at the end of this
|
||||
// block then we push the defined register into the stack.
|
||||
//
|
||||
ControlNode& node = *nodes[currentNode];
|
||||
RegisterPressure::Set* currentLiveOut = (liveOut != NULL) ? &liveOut[currentNode] : (RegisterPressure::Set*) 0;
|
||||
|
||||
InstructionList& phiNodes = node.getPhiNodeInstructions();
|
||||
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
|
||||
Instruction& phiNode = phiNodes.get(p);
|
||||
|
||||
InstructionUse* useEnd = phiNode.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = phiNode.getInstructionUseBegin(); usePtr < useEnd; usePtr++) {
|
||||
assert(usePtr->isRegister());
|
||||
RegisterName name = usePtr->getRegisterName();
|
||||
|
||||
if (copyStats[name].newName != NULL && copyStats[name].newName->newName != name)
|
||||
usePtr->setRegisterName(copyStats[name].newName->newName);
|
||||
}
|
||||
|
||||
if (currentLiveOut != NULL) {
|
||||
// This is a phi node and we have to push its defined name if it is live
|
||||
// at the end of the node. We only need to do this if the CFG has critical edges.
|
||||
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd() && phiNode.getInstructionDefineBegin()[0].isRegister());
|
||||
RegisterName name = phiNode.getInstructionDefineBegin()[0].getRegisterName();
|
||||
|
||||
if (currentLiveOut->test(name))
|
||||
pushName(pool, &(copyStats[name].newName), pushed, &pushedList, name, name);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
InstructionList& instructions = node.getInstructions();
|
||||
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
RegisterName name = usePtr->getRegisterName();
|
||||
|
||||
if (copyStats[name].newName != NULL && copyStats[name].newName->newName != name)
|
||||
usePtr->setRegisterName(copyStats[name].newName->newName);
|
||||
}
|
||||
}
|
||||
|
||||
// STEP2:
|
||||
// Look at this node's successors' phiNodes. We keep track of the number of time
|
||||
// a VR will be used by another copy instruction and insert each definition into the
|
||||
// destinationList. This is the only pass over this node's successors as we will
|
||||
// get all the information we need in the CopyData structures.
|
||||
//
|
||||
ControlEdge* successorEdgeEnd = node.getSuccessorsEnd();
|
||||
for (ControlEdge* successorEdgePtr = node.getSuccessorsBegin(); successorEdgePtr < successorEdgeEnd; successorEdgePtr++) {
|
||||
Uint32 useIndex = successorEdgePtr->getIndex();
|
||||
ControlNode& successor = successorEdgePtr->getTarget();
|
||||
|
||||
// Look at its phi nodes. The phi nodes are at the top of the instruction list. We exit
|
||||
// as soon as we find an instruction which is not a phi node
|
||||
InstructionList& phiNodes = successor.getPhiNodeInstructions();
|
||||
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
|
||||
Instruction& phiNode = phiNodes.get(p);
|
||||
|
||||
assert((phiNode.getInstructionUseBegin() + useIndex) < phiNode.getInstructionUseEnd());
|
||||
assert(phiNode.getInstructionDefineBegin() != phiNode.getInstructionDefineEnd());
|
||||
|
||||
InstructionUse& source = phiNode.getInstructionUseBegin()[useIndex];
|
||||
InstructionDefine& destination = phiNode.getInstructionDefineBegin()[0];
|
||||
|
||||
assert(source.isRegister() && destination.isRegister());
|
||||
|
||||
RegisterName sourceName = source.getRegisterName();
|
||||
RegisterName destinationName = destination.getRegisterName();
|
||||
|
||||
// Get the correct name for the source.
|
||||
if (copyStats[sourceName].newName != NULL)
|
||||
sourceName = copyStats[sourceName].newName->newName;
|
||||
|
||||
// Update the CopyData structures.
|
||||
if ((sourceName != rnInvalid) && (sourceName != destinationName)) {
|
||||
copyStats[destinationName].source = sourceName;
|
||||
copyStats[destinationName].classKind = destination.getRegisterClass();
|
||||
copyStats[destinationName].isLiveOut = (currentLiveOut != NULL) ? currentLiveOut->test(destinationName) : false;
|
||||
copyStats[destinationName].sourceNameToUse = destinationName;
|
||||
copyStats[sourceName].sourceNameToUse = sourceName;
|
||||
copyStats[sourceName].useCount++;
|
||||
destinationList.set(destinationName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// STEP3:
|
||||
// Insert into the worklist only the destination registers that will be not used in
|
||||
// another copy instruction in this block.
|
||||
//
|
||||
assert(workList.getSize() == 0);
|
||||
for (SparseSet::iterator d = destinationList.begin(); !destinationList.done(d); d = destinationList.advance(d)) {
|
||||
Uint32 dest = destinationList.get(d);
|
||||
if (copyStats[dest].useCount == 0)
|
||||
workList.set(dest);
|
||||
}
|
||||
|
||||
// STEP4:
|
||||
// Insert the copy instructions.
|
||||
//
|
||||
Uint32 destinationListSize = destinationList.getSize();
|
||||
InstructionList::iterator endOfTheNode = instructions.end();
|
||||
|
||||
// Find the right place to insert the copy instructions.
|
||||
if (destinationListSize != 0)
|
||||
while (instructions.get(endOfTheNode).getFlags() & ifControl)
|
||||
endOfTheNode = instructions.retreat(endOfTheNode);
|
||||
|
||||
while (destinationListSize != 0) {
|
||||
while(workList.getSize()) {
|
||||
RegisterName destinationName = RegisterName(workList.getOne());
|
||||
RegisterName sourceName = copyStats[destinationName].source;
|
||||
|
||||
workList.clear(destinationName);
|
||||
if (copyStats[destinationName].isLiveOut && !copyStats[destinationName].temporaryName) {
|
||||
// Lost copy problem.
|
||||
copyStats[destinationName].isLiveOut = false;
|
||||
|
||||
RegisterName sourceName = destinationName;
|
||||
RegisterClassKind classKind = copyStats[sourceName].classKind;
|
||||
RegisterName destinationName = getName(vrManager.newVirtualRegister(classKind));
|
||||
assert(destinationName < maxNameCount);
|
||||
|
||||
copyStats[destinationName].classKind = classKind;
|
||||
copyStats[sourceName].useCount = 0;
|
||||
|
||||
// We need to insert a copy to a temporary register to keep the
|
||||
// source register valid at the end of the node defining it.
|
||||
// This copy will be inserted right after the phi node defining it.
|
||||
RegisterName from = copyStats[sourceName].sourceNameToUse;
|
||||
Instruction* definingPhiNode = vrManager.getVirtualRegister(from).getDefiningInstruction();
|
||||
assert(definingPhiNode && (definingPhiNode->getFlags() & ifPhiNode) != 0);
|
||||
|
||||
RegisterID fromID = buildRegisterID(from, classKind);
|
||||
RegisterID toID = buildRegisterID(destinationName, classKind);
|
||||
Instruction& copy = emitter.newCopy(*definingPhiNode->getPrimitive(), fromID, toID);
|
||||
vrManager.getVirtualRegister(destinationName).setDefiningInstruction(copy);
|
||||
definingPhiNode->getPrimitive()->getContainer()->getInstructions().addFirst(copy);
|
||||
|
||||
copyStats[sourceName].temporaryName = destinationName;
|
||||
copyStats[sourceName].sourceNameToUse = destinationName;
|
||||
pushName(pool, &(copyStats[sourceName].newName), pushed, &pushedList, sourceName, destinationName);
|
||||
}
|
||||
|
||||
// Insert the copy instruction at the end of the current node.
|
||||
RegisterName from = copyStats[sourceName].sourceNameToUse;
|
||||
|
||||
RegisterClassKind classKind = copyStats[destinationName].classKind;
|
||||
RegisterID fromID = buildRegisterID(from, classKind);
|
||||
RegisterID toID = buildRegisterID(destinationName, classKind);
|
||||
Instruction& copy = emitter.newCopy(*vrManager.getVirtualRegister(from).getDefiningInstruction()->getPrimitive(), fromID, toID);
|
||||
instructions.insertAfter(copy, endOfTheNode);
|
||||
endOfTheNode = instructions.advance(endOfTheNode);
|
||||
|
||||
copyStats[sourceName].useCount = 0;
|
||||
if (destinationList.test(sourceName) && copyStats[sourceName].isLiveOut)
|
||||
pushName(pool, &(copyStats[sourceName].newName), pushed, &pushedList, sourceName, destinationName);
|
||||
copyStats[sourceName].isLiveOut = false;
|
||||
copyStats[sourceName].sourceNameToUse = destinationName;
|
||||
|
||||
if (destinationList.test(sourceName))
|
||||
workList.set(sourceName);
|
||||
destinationList.clear(destinationName);
|
||||
}
|
||||
|
||||
destinationListSize = destinationList.getSize();
|
||||
if (destinationListSize != 0) {
|
||||
RegisterName sourceName = RegisterName(destinationList.getOne());
|
||||
RegisterName destinationName;
|
||||
|
||||
if (!copyStats[sourceName].temporaryName) {
|
||||
// Cycle problem.
|
||||
RegisterClassKind classKind = copyStats[sourceName].classKind;
|
||||
destinationName = getName(vrManager.newVirtualRegister(classKind));
|
||||
assert(destinationName < maxNameCount);
|
||||
|
||||
copyStats[destinationName].classKind = classKind;
|
||||
copyStats[sourceName].temporaryName = destinationName;
|
||||
|
||||
// Insert the copy instruction at the end of the current node.
|
||||
RegisterName from = copyStats[sourceName].sourceNameToUse;
|
||||
|
||||
RegisterID fromID = buildRegisterID(from, classKind);
|
||||
RegisterID toID = buildRegisterID(destinationName, classKind);
|
||||
Instruction& copy = emitter.newCopy(*vrManager.getVirtualRegister(from).getDefiningInstruction()->getPrimitive(), fromID, toID);
|
||||
vrManager.getVirtualRegister(destinationName).setDefiningInstruction(copy);
|
||||
instructions.insertAfter(copy, endOfTheNode);
|
||||
endOfTheNode = instructions.advance(endOfTheNode);
|
||||
} else
|
||||
destinationName = copyStats[sourceName].temporaryName;
|
||||
|
||||
copyStats[sourceName].useCount = 0;
|
||||
copyStats[sourceName].isLiveOut = false;
|
||||
copyStats[sourceName].sourceNameToUse = destinationName;
|
||||
pushName(pool, &(copyStats[sourceName].newName), pushed, &pushedList, sourceName, destinationName);
|
||||
|
||||
workList.set(sourceName);
|
||||
}
|
||||
}
|
||||
|
||||
nodeStackPtr->pushedList = pushedList;
|
||||
nodeStackPtr->next = next;
|
||||
nodeStackPtr->limit = limit;
|
||||
++nodeStackPtr;
|
||||
next = dGraph.getSuccessorsBegin(currentNode);
|
||||
limit = dGraph.getSuccessorsEnd(currentNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // _PHI_NODE_REMOVER_H_
|
||||
155
mozilla/ef/Compiler/RegisterAllocator/RegisterAllocator.cpp
Normal file
155
mozilla/ef/Compiler/RegisterAllocator/RegisterAllocator.cpp
Normal file
@@ -0,0 +1,155 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "LogModule.h"
|
||||
#include "RegisterAllocator.h"
|
||||
#include "RegisterPressure.h"
|
||||
#include "RegisterAllocatorTools.h"
|
||||
#include "PhiNodeRemover.h"
|
||||
#include "LiveRange.h"
|
||||
#include "Liveness.h"
|
||||
#include "InterferenceGraph.h"
|
||||
#include "LiveRangeGraph.h"
|
||||
#include "Coalescing.h"
|
||||
#include "Spilling.h"
|
||||
#include "Coloring.h"
|
||||
#include "Splits.h"
|
||||
|
||||
class Pool;
|
||||
class ControlGraph;
|
||||
class VirtualRegisterManager;
|
||||
class InstructionEmitter;
|
||||
|
||||
UT_DEFINE_LOG_MODULE(RegAlloc);
|
||||
|
||||
void RegisterAllocator::allocateRegisters(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter)
|
||||
{
|
||||
// Insert the phi node instructions. We want to do this to have a single defined register per instruction.
|
||||
// If we keep the PhiNode (as a DataNode) and a PhiNode is of DoubleWordKind then we have to execute
|
||||
// some special code for the high word annotation.
|
||||
//
|
||||
RegisterAllocatorTools::insertPhiNodeInstructions(controlGraph, emitter);
|
||||
|
||||
// Perform some tests on the instruction graph.
|
||||
//
|
||||
DEBUG_ONLY(RegisterAllocatorTools::testTheInstructionGraph(controlGraph, vrManager));
|
||||
|
||||
// Replace the phi node instructions by their equivalent copy instructions.
|
||||
//
|
||||
PhiNodeRemover<LowRegisterPressure>::replacePhiNodes(controlGraph, vrManager, emitter);
|
||||
|
||||
// Do the register allocation.
|
||||
//
|
||||
RegisterAllocator registerAllocator(pool, controlGraph, vrManager, emitter);
|
||||
registerAllocator.doGraphColoring();
|
||||
}
|
||||
|
||||
void RegisterAllocator::doGraphColoring()
|
||||
{
|
||||
// Initialize the liverange map.
|
||||
//
|
||||
initLiveRanges();
|
||||
|
||||
// Build the live ranges. We do this to compress the number of RegisterNames
|
||||
// used in the insterference graph.
|
||||
//
|
||||
LiveRange<LowRegisterPressure>::build(*this);
|
||||
|
||||
// Remove unnecessary copies.
|
||||
//
|
||||
RegisterAllocatorTools::removeUnnecessaryCopies(*this);
|
||||
|
||||
for (Uint8 loop = 0; loop < 10; loop++) {
|
||||
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("********* RegisterAllocator loop %d *********\n", loop));
|
||||
|
||||
while(true) {
|
||||
// Build the interference graph.
|
||||
//
|
||||
iGraph.build();
|
||||
|
||||
// Coalesce the copy instructions.
|
||||
//
|
||||
if (!Coalescing<LowRegisterPressure>::coalesce(*this))
|
||||
break;
|
||||
}
|
||||
|
||||
// Print the interference graph.
|
||||
//
|
||||
DEBUG_LOG_ONLY(iGraph.printPretty(UT_LOG_MODULE(RegAlloc)));
|
||||
|
||||
// Calculate the spill costs.
|
||||
//
|
||||
Spilling<LowRegisterPressure>::calculateSpillCosts(*this);
|
||||
DEBUG_LOG_ONLY(RegisterAllocatorTools::printSpillCosts(*this));
|
||||
|
||||
// Calculate the split costs.
|
||||
//
|
||||
Splits<LowRegisterPressure>::calculateSplitCosts(*this);
|
||||
DEBUG_LOG_ONLY(RegisterAllocatorTools::printSplitCosts(*this));
|
||||
|
||||
// Build the live range graph.
|
||||
//
|
||||
lGraph.build();
|
||||
DEBUG_LOG_ONLY(lGraph.printPretty(UT_LOG_MODULE(RegAlloc)));
|
||||
|
||||
// Color the graph. If it succeeds then we're done with the
|
||||
// register allocation.
|
||||
//
|
||||
if (Coloring<LowRegisterPressure>::color(*this)) {
|
||||
// Write the final colors in the instruction graph.
|
||||
//
|
||||
Coloring<LowRegisterPressure>::finalColoring(*this);
|
||||
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("********** RegisterAllocator done **********\n"));
|
||||
DEBUG_LOG_ONLY(RegisterAllocatorTools::printInstructions(*this));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// We need to spill some registers.
|
||||
//
|
||||
Spilling<LowRegisterPressure>::insertSpillCode(*this);
|
||||
|
||||
// Insert the split instructions.
|
||||
//
|
||||
Splits<LowRegisterPressure>::insertSplitCode(*this);
|
||||
|
||||
// Update the live ranges.
|
||||
//
|
||||
// FIX
|
||||
}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
RegisterAllocatorTools::updateInstructionGraph(*this);
|
||||
RegisterAllocatorTools::printInstructions(*this);
|
||||
#endif
|
||||
fprintf(stderr, "!!! Coloring failed after 10 loops !!!\n");
|
||||
abort();
|
||||
}
|
||||
|
||||
void RegisterAllocator::initLiveRanges()
|
||||
{
|
||||
Uint32 count = this->nameCount;
|
||||
RegisterName* name2range = new(pool) RegisterName[nameCount];
|
||||
for (RegisterName r = RegisterName(1); r < count; r = RegisterName(r + 1))
|
||||
name2range[r] = r;
|
||||
this->name2range = name2range;
|
||||
rangeCount = count;
|
||||
}
|
||||
88
mozilla/ef/Compiler/RegisterAllocator/RegisterAllocator.h
Normal file
88
mozilla/ef/Compiler/RegisterAllocator/RegisterAllocator.h
Normal file
@@ -0,0 +1,88 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _REGISTER_ALLOCATOR_H_
|
||||
#define _REGISTER_ALLOCATOR_H_
|
||||
|
||||
class Pool;
|
||||
class ControlGraph;
|
||||
class InstructionEmitter;
|
||||
struct SpillCost;
|
||||
struct SplitCost;
|
||||
|
||||
#include "Liveness.h"
|
||||
#include "VirtualRegister.h"
|
||||
#include "RegisterPressure.h" // This should included by Backend.cpp
|
||||
#include "InterferenceGraph.h"
|
||||
#include "LiveRangeGraph.h"
|
||||
|
||||
//template <class RegisterPressure>
|
||||
class RegisterAllocator
|
||||
{
|
||||
public:
|
||||
|
||||
Pool& pool; //
|
||||
ControlGraph& controlGraph; //
|
||||
VirtualRegisterManager& vrManager; //
|
||||
InstructionEmitter& emitter; //
|
||||
|
||||
RegisterName* name2range; //
|
||||
RegisterName* color; //
|
||||
SpillCost* spillCost; //
|
||||
SparseSet* willSpill; //
|
||||
SplitCost* splitCost; //
|
||||
NameLinkedList** splitAround; //
|
||||
InterferenceGraph<LowRegisterPressure> iGraph; //
|
||||
LiveRangeGraph<LowRegisterPressure> lGraph; //
|
||||
LivenessInfo<LowRegisterPressure> liveness; //
|
||||
Uint32 nameCount; //
|
||||
Uint32 rangeCount; //
|
||||
bool splitFound; //
|
||||
|
||||
private:
|
||||
|
||||
//
|
||||
//
|
||||
void doGraphColoring();
|
||||
|
||||
public:
|
||||
|
||||
//
|
||||
//
|
||||
inline RegisterAllocator(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter);
|
||||
|
||||
//
|
||||
//
|
||||
bool canInterfere(RegisterName /*name1*/, RegisterName /*name2*/) const {return true;}
|
||||
|
||||
//
|
||||
//
|
||||
void initLiveRanges();
|
||||
|
||||
//
|
||||
//
|
||||
static void allocateRegisters(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter);
|
||||
};
|
||||
|
||||
//
|
||||
//
|
||||
inline RegisterAllocator::RegisterAllocator(Pool& pool, ControlGraph& controlGraph, VirtualRegisterManager& vrManager, InstructionEmitter& emitter)
|
||||
: pool(pool), controlGraph(controlGraph), vrManager(vrManager), emitter(emitter), iGraph(*this), lGraph(*this), nameCount(vrManager.getSize()) {}
|
||||
|
||||
#endif // _REGISTER_ALLOCATOR_H_
|
||||
|
||||
355
mozilla/ef/Compiler/RegisterAllocator/RegisterAllocatorTools.cpp
Normal file
355
mozilla/ef/Compiler/RegisterAllocator/RegisterAllocatorTools.cpp
Normal file
@@ -0,0 +1,355 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "LogModule.h"
|
||||
#include "RegisterAllocatorTools.h"
|
||||
#include "Pool.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "ControlNodes.h"
|
||||
#include "Primitives.h"
|
||||
#include "InstructionEmitter.h"
|
||||
#include "Instruction.h"
|
||||
#include "RegisterAllocator.h"
|
||||
#include "Spilling.h"
|
||||
#include "Splits.h"
|
||||
#include "BitSet.h"
|
||||
|
||||
UT_EXTERN_LOG_MODULE(RegAlloc);
|
||||
|
||||
#ifdef DEBUG
|
||||
void RegisterAllocatorTools::testTheInstructionGraph(ControlGraph& controlGraph, VirtualRegisterManager& vrManager)
|
||||
{
|
||||
// Test the declared VirtualRegisters. The register allocator tries to condense the register universe.
|
||||
// Any gap in the VirtualRegister names will be a loss of efficiency !!!!
|
||||
|
||||
Uint32 nameCount = vrManager.getSize();
|
||||
BitSet registerSeen(controlGraph.pool, nameCount);
|
||||
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
|
||||
InstructionList& instructions = nodes[n]->getInstructions();
|
||||
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister())
|
||||
registerSeen.set(usePtr->getRegisterName());
|
||||
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
registerSeen.set(definePtr->getRegisterName());
|
||||
}
|
||||
|
||||
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
|
||||
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
|
||||
Instruction& instruction = phiNodes.get(p);
|
||||
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister())
|
||||
registerSeen.set(usePtr->getRegisterName());
|
||||
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
registerSeen.set(definePtr->getRegisterName());
|
||||
}
|
||||
}
|
||||
|
||||
bool renameRegisters = false;
|
||||
for (BitSet::iterator i = registerSeen.nextZero(0); !registerSeen.done(i); i = registerSeen.nextZero(i)) {
|
||||
renameRegisters = true;
|
||||
fprintf(stderr,
|
||||
"WARNING: The VirtualRegister vr%d has been allocated during CodeGeneration but\n"
|
||||
" is never used nor defined by any instruction in the instruction graph\n"
|
||||
" PLEASE FIX \n",
|
||||
i);
|
||||
}
|
||||
if (renameRegisters) {
|
||||
Instruction** definingInstruction = new Instruction*[nameCount];
|
||||
memset(definingInstruction, '\0', nameCount * sizeof(Instruction*));
|
||||
RegisterName* newName = new RegisterName[nameCount];
|
||||
memset(newName, '\0', nameCount * sizeof(RegisterName));
|
||||
RegisterName nextName = RegisterName(1);
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
|
||||
InstructionList& instructions = nodes[n]->getInstructions();
|
||||
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
RegisterName name = usePtr->getRegisterName();
|
||||
if (newName[name] == rnInvalid) {
|
||||
newName[name] = nextName;
|
||||
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
|
||||
nextName = RegisterName(nextName + 1);
|
||||
}
|
||||
usePtr->setRegisterName(newName[name]);
|
||||
}
|
||||
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister()) {
|
||||
RegisterName name = definePtr->getRegisterName();
|
||||
if (newName[name] == rnInvalid) {
|
||||
newName[name] = nextName;
|
||||
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
|
||||
nextName = RegisterName(nextName + 1);
|
||||
}
|
||||
definePtr->setRegisterName(newName[name]);
|
||||
}
|
||||
}
|
||||
|
||||
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
|
||||
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
|
||||
Instruction& instruction = phiNodes.get(p);
|
||||
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
RegisterName name = usePtr->getRegisterName();
|
||||
if (newName[name] == rnInvalid) {
|
||||
newName[name] = nextName;
|
||||
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
|
||||
nextName = RegisterName(nextName + 1);
|
||||
}
|
||||
usePtr->setRegisterName(newName[name]);
|
||||
}
|
||||
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister()) {
|
||||
RegisterName name = definePtr->getRegisterName();
|
||||
if (newName[name] == rnInvalid) {
|
||||
newName[name] = nextName;
|
||||
definingInstruction[nextName] = vrManager.getVirtualRegister(name).getDefiningInstruction();
|
||||
nextName = RegisterName(nextName + 1);
|
||||
}
|
||||
definePtr->setRegisterName(newName[name]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vrManager.setSize(nextName);
|
||||
|
||||
for (RegisterName r = RegisterName(1); r < nextName; r = RegisterName(r + 1))
|
||||
vrManager.getVirtualRegister(r).definingInstruction = definingInstruction[r];
|
||||
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("RegisterMap:\n"));
|
||||
for (Uint32 i = 1; i < nameCount; i++)
|
||||
if (newName[i] != 0)
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tvr%d becomes vr%d.\n", i, newName[i]));
|
||||
else
|
||||
UT_OBJECTLOG(UT_LOG_MODULE(RegAlloc), PR_LOG_ALWAYS, ("\tvr%d is dead.\n", i));
|
||||
|
||||
|
||||
delete newName;
|
||||
delete definingInstruction;
|
||||
}
|
||||
|
||||
}
|
||||
#endif // DEBUG
|
||||
|
||||
void RegisterAllocatorTools::removeUnnecessaryCopies(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
ControlGraph& controlGraph = registerAllocator.controlGraph;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
InstructionList& instructions = nodes[n]->getInstructions();
|
||||
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i);) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
i = instructions.advance(i);
|
||||
|
||||
if (instruction.getFlags() & ifCopy) {
|
||||
assert(instruction.getInstructionUseBegin() != instruction.getInstructionUseEnd() && instruction.getInstructionUseBegin()[0].isRegister());
|
||||
assert(instruction.getInstructionDefineBegin() != instruction.getInstructionDefineEnd() && instruction.getInstructionDefineBegin()[0].isRegister());
|
||||
|
||||
RegisterName source = name2range[instruction.getInstructionUseBegin()[0].getRegisterName()];
|
||||
RegisterName destination = name2range[instruction.getInstructionDefineBegin()[0].getRegisterName()];
|
||||
|
||||
if (source == destination)
|
||||
instruction.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void RegisterAllocatorTools::updateInstructionGraph(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
ControlGraph& controlGraph = registerAllocator.controlGraph;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
InstructionList& instructions = nodes[n]->getInstructions();
|
||||
for (InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister())
|
||||
usePtr->setRegisterName(name2range[usePtr->getRegisterName()]);
|
||||
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
definePtr->setRegisterName(name2range[definePtr->getRegisterName()]);
|
||||
}
|
||||
|
||||
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
|
||||
for (InstructionList::iterator p = phiNodes.begin(); !phiNodes.done(p); p = phiNodes.advance(p)) {
|
||||
Instruction& instruction = phiNodes.get(p);
|
||||
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
for (InstructionUse* usePtr = instruction.getInstructionUseBegin(); usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister())
|
||||
usePtr->setRegisterName(name2range[usePtr->getRegisterName()]);
|
||||
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
for (InstructionDefine* definePtr = instruction.getInstructionDefineBegin(); definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
definePtr->setRegisterName(name2range[definePtr->getRegisterName()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void RegisterAllocatorTools::insertPhiNodeInstructions(ControlGraph& controlGraph, InstructionEmitter& emitter)
|
||||
{
|
||||
Pool& pool = controlGraph.pool;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
ControlNode& node = *nodes[n];
|
||||
DoublyLinkedList<PhiNode>& phiNodes = node.getPhiNodes();
|
||||
|
||||
if (!phiNodes.empty()) {
|
||||
|
||||
// Set the index of the incoming edges.
|
||||
Uint32 index = 0;
|
||||
const DoublyLinkedList<ControlEdge>& predecessors = node.getPredecessors();
|
||||
for (DoublyLinkedList<ControlEdge>::iterator p = predecessors.begin(); !predecessors.done(p); p = predecessors.advance(p))
|
||||
predecessors.get(p).setIndex(index++);
|
||||
|
||||
// Insert the phi node instruction in the instruction list.
|
||||
for (DoublyLinkedList<PhiNode>::iterator i = phiNodes.begin(); !phiNodes.done(i); i = phiNodes.advance(i)) {
|
||||
PhiNode& phiNode = phiNodes.get(i);
|
||||
ValueKind kind = phiNode.getKind();
|
||||
|
||||
if (!isStorableKind(kind))
|
||||
continue;
|
||||
|
||||
RegisterClassKind classKind = rckGeneral; // FIX: get class kind from phi node kind.
|
||||
Uint32 nInputs = phiNode.nInputs();
|
||||
|
||||
PhiNodeInstruction& phiNodeInstruction = *new(pool) PhiNodeInstruction(&phiNode, pool, nInputs);
|
||||
|
||||
emitter.defineProducer(phiNode, phiNodeInstruction, 0, classKind, drLow);
|
||||
for (Uint32 whichInput = 0; whichInput < nInputs; whichInput++)
|
||||
emitter.useProducer(phiNode.nthInputVariable(whichInput), phiNodeInstruction, whichInput, classKind, drLow);
|
||||
|
||||
node.addPhiNodeInstruction(phiNodeInstruction);
|
||||
|
||||
if (isDoublewordKind(kind)) {
|
||||
PhiNodeInstruction& phiNodeInstruction = *new(pool) PhiNodeInstruction(&phiNode, pool, nInputs);
|
||||
|
||||
emitter.defineProducer(phiNode, phiNodeInstruction, 0, classKind, drHigh);
|
||||
for (Uint32 whichInput = 0; whichInput < nInputs; whichInput++)
|
||||
emitter.useProducer(phiNode.nthInputVariable(whichInput), phiNodeInstruction, whichInput, classKind, drHigh);
|
||||
|
||||
node.addPhiNodeInstruction(phiNodeInstruction);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
|
||||
void RegisterAllocatorTools::printSpillCosts(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
LogModuleObject log = UT_LOG_MODULE(RegAlloc);
|
||||
Uint32 rangeCount = registerAllocator.rangeCount;
|
||||
SpillCost* cost = registerAllocator.spillCost;
|
||||
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Spill costs:\n"));
|
||||
for (Uint32 i = 1; i < rangeCount; i++) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\trange %d : ", i));
|
||||
if (cost[i].infinite)
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("infinite\n"));
|
||||
else
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("%f\n", cost[i].cost));
|
||||
}
|
||||
}
|
||||
|
||||
void RegisterAllocatorTools::printSplitCosts(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
LogModuleObject log = UT_LOG_MODULE(RegAlloc);
|
||||
Uint32 rangeCount = registerAllocator.rangeCount;
|
||||
SplitCost* cost = registerAllocator.splitCost;
|
||||
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("Split costs:\n"));
|
||||
for (Uint32 i = 1; i < rangeCount; i++) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\trange %d : loads = %f stores = %f\n", i, cost[i].loads, cost[i].stores));
|
||||
}
|
||||
}
|
||||
|
||||
void RegisterAllocatorTools::printInstructions(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
LogModuleObject log = UT_LOG_MODULE(RegAlloc);
|
||||
ControlNode** nodes = registerAllocator.controlGraph.dfsList;
|
||||
Uint32 nNodes = registerAllocator.controlGraph.nNodes;
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("N%d:\n", n));
|
||||
|
||||
InstructionList& phiNodes = nodes[n]->getPhiNodeInstructions();
|
||||
InstructionList& instructions = nodes[n]->getInstructions();
|
||||
|
||||
if (!phiNodes.empty()) {
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" PhiNodes:\n", n));
|
||||
for(InstructionList::iterator i = phiNodes.begin(); !phiNodes.done(i); i = phiNodes.advance(i)) {
|
||||
phiNodes.get(i).printPretty(log);
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
|
||||
}
|
||||
if (!instructions.empty())
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, (" Instructions:\n", n));
|
||||
}
|
||||
|
||||
for(InstructionList::iterator i = instructions.begin(); !instructions.done(i); i = instructions.advance(i)) {
|
||||
instructions.get(i).printPretty(log);
|
||||
UT_OBJECTLOG(log, PR_LOG_ALWAYS, ("\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif // DEBUG_LOG
|
||||
117
mozilla/ef/Compiler/RegisterAllocator/RegisterAllocatorTools.h
Normal file
117
mozilla/ef/Compiler/RegisterAllocator/RegisterAllocatorTools.h
Normal file
@@ -0,0 +1,117 @@
|
||||
// -*- mode:C++; tab-width:4; truncate-lines:t -*-
|
||||
//
|
||||
// CONFIDENTIAL AND PROPRIETARY SOURCE CODE OF
|
||||
// NETSCAPE COMMUNICATIONS CORPORATION
|
||||
// Copyright © 1996, 1997 Netscape Communications Corporation. All Rights
|
||||
// Reserved. Use of this Source Code is subject to the terms of the
|
||||
// applicable license agreement from Netscape Communications Corporation.
|
||||
// The copyright notice(s) in this Source Code does not indicate actual or
|
||||
// intended publication of this Source Code.
|
||||
//
|
||||
// $Id: RegisterAllocatorTools.h,v 1.1.2.1 1999-03-02 16:12:05 fur%netscape.com Exp $
|
||||
//
|
||||
|
||||
#ifndef _REGISTER_ALLOCATOR_TOOLS_H_
|
||||
#define _REGISTER_ALLOCATOR_TOOLS_H_
|
||||
|
||||
#include "LogModule.h"
|
||||
#include "RegisterTypes.h"
|
||||
#include <string.h>
|
||||
|
||||
class RegisterAllocator;
|
||||
class ControlGraph;
|
||||
class InstructionEmitter;
|
||||
class VirtualRegisterManager;
|
||||
|
||||
struct RegisterAllocatorTools
|
||||
{
|
||||
//
|
||||
//
|
||||
static void insertPhiNodeInstructions(ControlGraph& controlGraph, InstructionEmitter& emitter);
|
||||
|
||||
//
|
||||
//
|
||||
static void updateInstructionGraph(RegisterAllocator& registerAllocator);
|
||||
|
||||
//
|
||||
//
|
||||
static void removeUnnecessaryCopies(RegisterAllocator& registerAllocator);
|
||||
|
||||
#ifdef DEBUG
|
||||
//
|
||||
//
|
||||
static void testTheInstructionGraph(ControlGraph& controlGraph, VirtualRegisterManager& vrManager);
|
||||
#endif // DEBUG
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
//
|
||||
//
|
||||
static void printInstructions(RegisterAllocator& registerAllocator);
|
||||
|
||||
//
|
||||
//
|
||||
static void printSpillCosts(RegisterAllocator& registerAllocator);
|
||||
|
||||
//
|
||||
//
|
||||
static void printSplitCosts(RegisterAllocator& registerAllocator);
|
||||
#endif // DEBUG_LOG
|
||||
};
|
||||
|
||||
//
|
||||
// FIX: this should go in a class (LookupTable ?)
|
||||
//
|
||||
|
||||
inline RegisterName findRoot(RegisterName name, RegisterName* table)
|
||||
{
|
||||
RegisterName* stack = table;
|
||||
RegisterName* stackPtr = stack;
|
||||
|
||||
RegisterName newName;
|
||||
while((newName = table[name]) != name) {
|
||||
*--stackPtr = name;
|
||||
name = newName;
|
||||
}
|
||||
|
||||
while (stackPtr != stack)
|
||||
table[*stackPtr++] = name;
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
inline void init(RegisterName* table, Uint32 nameCount)
|
||||
{
|
||||
for (RegisterName r = RegisterName(0); r < nameCount; r = RegisterName(r + 1))
|
||||
table[r] = r;
|
||||
}
|
||||
|
||||
inline Uint32 compress(RegisterName* name2range, RegisterName* table, Uint32 nameCount, Uint32 tableSize)
|
||||
{
|
||||
RegisterName* liveRange = new RegisterName[tableSize];
|
||||
memset(liveRange, '\0', tableSize * sizeof(RegisterName));
|
||||
|
||||
// Update the lookup table.
|
||||
for (RegisterName r = RegisterName(1); r < tableSize; r = RegisterName(r + 1))
|
||||
findRoot(r, table);
|
||||
|
||||
// Count the liveranges.
|
||||
Uint32 liveRangeCount = 1;
|
||||
for (RegisterName s = RegisterName(1); s < tableSize; s = RegisterName(s + 1))
|
||||
if (table[s] == s)
|
||||
liveRange[s] = RegisterName(liveRangeCount++);
|
||||
|
||||
for (RegisterName t = RegisterName(1); t < nameCount; t = RegisterName(t + 1))
|
||||
name2range[t] = liveRange[table[name2range[t]]];
|
||||
|
||||
return liveRangeCount;
|
||||
}
|
||||
|
||||
inline double doLog10(Uint32 power)
|
||||
{
|
||||
double log = 1.0;
|
||||
while (power--)
|
||||
log *= 10.0;
|
||||
return log;
|
||||
}
|
||||
|
||||
#endif // _REGISTER_ALLOCATOR_TOOLS_H_
|
||||
38
mozilla/ef/Compiler/RegisterAllocator/RegisterAssigner.h
Normal file
38
mozilla/ef/Compiler/RegisterAllocator/RegisterAssigner.h
Normal file
@@ -0,0 +1,38 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _REGISTER_ASSIGNER_H_
|
||||
#define _REGISTER_ASSIGNER_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "VirtualRegister.h"
|
||||
|
||||
class FastBitMatrix;
|
||||
|
||||
class RegisterAssigner
|
||||
{
|
||||
protected:
|
||||
VirtualRegisterManager& vRegManager;
|
||||
|
||||
public:
|
||||
RegisterAssigner(VirtualRegisterManager& vrMan) : vRegManager(vrMan) {}
|
||||
|
||||
virtual bool assignRegisters(FastBitMatrix& interferenceMatrix) = 0;
|
||||
};
|
||||
|
||||
#endif /* _REGISTER_ASSIGNER_H_ */
|
||||
25
mozilla/ef/Compiler/RegisterAllocator/RegisterClass.h
Normal file
25
mozilla/ef/Compiler/RegisterAllocator/RegisterClass.h
Normal file
@@ -0,0 +1,25 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _REGISTER_CLASS_H_
|
||||
#define _REGISTER_CLASS_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "RegisterTypes.h"
|
||||
|
||||
#endif // _REGISTER_CLASS_H_
|
||||
37
mozilla/ef/Compiler/RegisterAllocator/RegisterPressure.h
Normal file
37
mozilla/ef/Compiler/RegisterAllocator/RegisterPressure.h
Normal file
@@ -0,0 +1,37 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _REGISTER_PRESSURE_H_
|
||||
#define _REGISTER_PRESSURE_H_
|
||||
|
||||
#include "BitSet.h"
|
||||
#include "HashSet.h"
|
||||
|
||||
struct LowRegisterPressure
|
||||
{
|
||||
typedef BitSet Set;
|
||||
static const bool setIsOrdered = true;
|
||||
};
|
||||
|
||||
struct HighRegisterPressure
|
||||
{
|
||||
typedef HashSet Set;
|
||||
static const bool setIsOrdered = false;
|
||||
};
|
||||
|
||||
#endif // _REGISTER_PRESSURE_H_
|
||||
104
mozilla/ef/Compiler/RegisterAllocator/RegisterTypes.h
Normal file
104
mozilla/ef/Compiler/RegisterAllocator/RegisterTypes.h
Normal file
@@ -0,0 +1,104 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _REGISTER_TYPES_H_
|
||||
#define _REGISTER_TYPES_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// RegisterName -
|
||||
//
|
||||
|
||||
enum RegisterName {
|
||||
rnInvalid = 0,
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// RegisterClassKind -
|
||||
//
|
||||
|
||||
enum RegisterClassKind {
|
||||
rckInvalid = 0,
|
||||
rckGeneral,
|
||||
rckStackSlot,
|
||||
|
||||
nRegisterClassKind
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// RegisterID -
|
||||
//
|
||||
|
||||
enum RegisterID {
|
||||
invalidID = 0
|
||||
};
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// RegisterKind -
|
||||
//
|
||||
|
||||
enum RegisterKind {
|
||||
rkCallerSave = 0,
|
||||
rkCalleeSave,
|
||||
};
|
||||
|
||||
struct NameLinkedList {
|
||||
RegisterName name;
|
||||
NameLinkedList* next;
|
||||
};
|
||||
|
||||
#ifdef DEBUG
|
||||
|
||||
const registerNameMask = 0x03ffffff;
|
||||
const coloredRegisterMask = 0x04000000;
|
||||
const machineRegisterMask = 0x08000000;
|
||||
const registerClassMask = 0xf0000000;
|
||||
|
||||
const registerNameShift = 0;
|
||||
const coloredRegisterShift = 26;
|
||||
const machineRegisterShift = 27;
|
||||
const registerClassShift = 28;
|
||||
|
||||
#else // DEBUG
|
||||
|
||||
const registerNameMask = 0x0fffffff;
|
||||
const registerClassMask = 0xf0000000;
|
||||
|
||||
const registerNameShift = 0;
|
||||
const registerClassShift = 28;
|
||||
|
||||
#endif // DEBUG
|
||||
|
||||
|
||||
inline RegisterClassKind getClass(RegisterID registerID) {return RegisterClassKind((registerID & registerClassMask) >> registerClassShift);}
|
||||
inline RegisterName getName(RegisterID registerID) {return RegisterName((registerID & registerNameMask) >> registerNameShift);}
|
||||
inline void setClass(RegisterID& registerID, RegisterClassKind classKind) {registerID = RegisterID((registerID & ~registerClassMask) | ((classKind << registerClassShift) & registerClassMask));}
|
||||
inline void setName(RegisterID& registerID, RegisterName name) {assert((name & ~registerNameMask) == 0); registerID = RegisterID((registerID & ~registerNameMask) | ((name << registerNameShift) & registerNameMask));}
|
||||
inline RegisterID buildRegisterID(RegisterName name, RegisterClassKind classKind) {return RegisterID(((classKind << registerClassShift) & registerClassMask) | ((name << registerNameShift) & registerNameMask));}
|
||||
|
||||
#ifdef DEBUG
|
||||
|
||||
inline bool isMachineRegister(RegisterID rid) {return (rid & machineRegisterMask) != 0;}
|
||||
inline void setMachineRegister(RegisterID& rid) {rid = RegisterID(rid | machineRegisterMask);}
|
||||
inline bool isColoredRegister(RegisterID rid) {return (rid & coloredRegisterMask) != 0;}
|
||||
inline void setColoredRegister(RegisterID& rid) {rid = RegisterID(rid | coloredRegisterMask);}
|
||||
|
||||
#endif // DEBUG
|
||||
|
||||
#endif // _REGISTER_TYPES_H_
|
||||
32
mozilla/ef/Compiler/RegisterAllocator/SSATools.cpp
Normal file
32
mozilla/ef/Compiler/RegisterAllocator/SSATools.cpp
Normal file
@@ -0,0 +1,32 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "SSATools.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "VirtualRegister.h"
|
||||
#include "Liveness.h"
|
||||
|
||||
void replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager)
|
||||
{
|
||||
if (!controlGraph.hasBackEdges)
|
||||
return;
|
||||
|
||||
Liveness liveness(controlGraph.pool);
|
||||
liveness.buildLivenessAnalysis(controlGraph, vrManager);
|
||||
}
|
||||
29
mozilla/ef/Compiler/RegisterAllocator/SSATools.h
Normal file
29
mozilla/ef/Compiler/RegisterAllocator/SSATools.h
Normal file
@@ -0,0 +1,29 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SSA_TOOLS_H_
|
||||
#define _SSA_TOOLS_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
|
||||
class ControlGraph;
|
||||
class VirtualRegisterManager;
|
||||
|
||||
extern void replacePhiNodes(ControlGraph& controlGraph, VirtualRegisterManager& vrManager);
|
||||
|
||||
#endif // _SSA_TOOLS_H_
|
||||
37
mozilla/ef/Compiler/RegisterAllocator/SparseSet.cpp
Normal file
37
mozilla/ef/Compiler/RegisterAllocator/SparseSet.cpp
Normal file
@@ -0,0 +1,37 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "SparseSet.h"
|
||||
#include "BitSet.h"
|
||||
#include "Pool.h"
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
// Print the set.
|
||||
//
|
||||
void SparseSet::printPretty(LogModuleObject log)
|
||||
{
|
||||
Pool pool;
|
||||
BitSet set(pool, universeSize);
|
||||
|
||||
for (Uint32 i = 0; i < count; i++)
|
||||
set.set(node[i].element);
|
||||
|
||||
set.printPretty(log);
|
||||
}
|
||||
#endif // DEBUG_LOG
|
||||
168
mozilla/ef/Compiler/RegisterAllocator/SparseSet.h
Normal file
168
mozilla/ef/Compiler/RegisterAllocator/SparseSet.h
Normal file
@@ -0,0 +1,168 @@
|
||||
// -*- mode:C++; tab-width:4; truncate-lines:t -*-
|
||||
//
|
||||
// CONFIDENTIAL AND PROPRIETARY SOURCE CODE OF
|
||||
// NETSCAPE COMMUNICATIONS CORPORATION
|
||||
// Copyright © 1996, 1997 Netscape Communications Corporation. All Rights
|
||||
// Reserved. Use of this Source Code is subject to the terms of the
|
||||
// applicable license agreement from Netscape Communications Corporation.
|
||||
// The copyright notice(s) in this Source Code does not indicate actual or
|
||||
// intended publication of this Source Code.
|
||||
//
|
||||
// $Id: SparseSet.h,v 1.1.2.1 1999-03-02 16:12:07 fur%netscape.com Exp $
|
||||
//
|
||||
|
||||
#ifndef _SPARSE_SET_H_
|
||||
#define _SPARSE_SET_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "Pool.h"
|
||||
#include "LogModule.h"
|
||||
#include "BitSet.h"
|
||||
|
||||
class SparseSet
|
||||
{
|
||||
private:
|
||||
|
||||
struct Node {
|
||||
Uint32 element;
|
||||
Uint32 stackIndex;
|
||||
};
|
||||
|
||||
Node* node;
|
||||
Uint32 count;
|
||||
Uint32 universeSize;
|
||||
|
||||
private:
|
||||
|
||||
// No copy constructor.
|
||||
SparseSet(const SparseSet&);
|
||||
|
||||
// Check if the given set's universe is of the same size than this universe.
|
||||
void checkUniverseCompatibility(const SparseSet& set) const {assert(set.universeSize == universeSize);}
|
||||
// Check if pos is valid for this set's universe.
|
||||
void checkMember(Int32 pos) const {assert(pos >=0 && Uint32(pos) < universeSize);}
|
||||
|
||||
public:
|
||||
|
||||
SparseSet(Pool& pool, Uint32 universeSize) : universeSize(universeSize) {node = new(pool) Node[universeSize]; clear();}
|
||||
|
||||
// Clear the sparse set.
|
||||
void clear() {count = 0;}
|
||||
// Clear the element at index.
|
||||
inline void clear(Uint32 index);
|
||||
// Set the element at index.
|
||||
inline void set(Uint32 index);
|
||||
// Return true if the element at index is set.
|
||||
inline bool test(Uint32 index) const;
|
||||
// Union with the given sparse set.
|
||||
inline void or(const SparseSet& set);
|
||||
// Intersection with the given sparse set.
|
||||
inline void and(const SparseSet& set);
|
||||
// Difference with the given sparse set.
|
||||
inline void difference(const SparseSet& set);
|
||||
// Copy set.
|
||||
inline SparseSet& operator = (const SparseSet& set);
|
||||
inline SparseSet& operator = (const BitSet& set);
|
||||
// Return true if the sparse sets are identical.
|
||||
friend bool operator == (const SparseSet& set1, const SparseSet& set2);
|
||||
// Return true if the sparse sets are different.
|
||||
friend bool operator != (const SparseSet& set1, const SparseSet& set2);
|
||||
|
||||
// Logical operators.
|
||||
SparseSet& operator |= (const SparseSet& set) {or(set); return *this;}
|
||||
SparseSet& operator &= (const SparseSet& set) {and(set); return *this;}
|
||||
SparseSet& operator -= (const SparseSet& set) {difference(set); return *this;}
|
||||
|
||||
// Iterator to conform with the set API.
|
||||
typedef Int32 iterator;
|
||||
// Return the iterator for the first element of this set.
|
||||
iterator begin() const {return count - 1;}
|
||||
// Return the next iterator.
|
||||
iterator advance(iterator pos) const {return --pos;}
|
||||
// Return true if the iterator is at the end of the set.
|
||||
bool done(iterator pos) const {return pos < 0;}
|
||||
// Return the element for the given iterator;
|
||||
Uint32 get(iterator pos) const {return node[pos].element;}
|
||||
// Return one element of this set.
|
||||
Uint32 getOne() const {assert(count > 0); return node[0].element;}
|
||||
// Return the size of this set.
|
||||
Uint32 getSize() const {return count;}
|
||||
|
||||
#ifdef DEBUG_LOG
|
||||
// Print the set.
|
||||
void printPretty(LogModuleObject log);
|
||||
#endif // DEBUG_LOG
|
||||
};
|
||||
|
||||
inline void SparseSet::clear(Uint32 element)
|
||||
{
|
||||
checkMember(element);
|
||||
Uint32 count = this->count;
|
||||
Node* node = this->node;
|
||||
|
||||
Uint32 stackIndex = node[element].stackIndex;
|
||||
|
||||
if ((stackIndex < count) && (node[stackIndex].element == element)) {
|
||||
Uint32 stackTop = node[count - 1].element;
|
||||
|
||||
node[stackIndex].element = stackTop;
|
||||
node[stackTop].stackIndex = stackIndex;
|
||||
this->count = count - 1;
|
||||
}
|
||||
}
|
||||
|
||||
inline void SparseSet::set(Uint32 element)
|
||||
{
|
||||
checkMember(element);
|
||||
Uint32 count = this->count;
|
||||
Node* node = this->node;
|
||||
|
||||
Uint32 stackIndex = node[element].stackIndex;
|
||||
|
||||
if ((stackIndex >= count) || (node[stackIndex].element != element)) {
|
||||
node[count].element = element;
|
||||
node[element].stackIndex = count;
|
||||
this->count = count + 1;
|
||||
}
|
||||
}
|
||||
|
||||
inline bool SparseSet::test(Uint32 element) const
|
||||
{
|
||||
checkMember(element);
|
||||
Node* node = this->node;
|
||||
|
||||
Uint32 stackIndex = node[element].stackIndex;
|
||||
return ((stackIndex < count) && (node[stackIndex].element == element));
|
||||
}
|
||||
|
||||
inline SparseSet& SparseSet::operator = (const SparseSet& set)
|
||||
{
|
||||
checkUniverseCompatibility(set);
|
||||
Uint32 sourceCount = set.getSize();
|
||||
Node* node = this->node;
|
||||
|
||||
memcpy(node, set.node, sourceCount * sizeof(Node));
|
||||
|
||||
for (Uint32 i = 0; i < sourceCount; i++) {
|
||||
Uint32 element = node[i].element;
|
||||
node[element].stackIndex = i;
|
||||
}
|
||||
|
||||
count = sourceCount;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
inline SparseSet& SparseSet::operator = (const BitSet& set)
|
||||
{
|
||||
// FIX: there's room for optimization here.
|
||||
assert(universeSize == set.getSize());
|
||||
|
||||
clear();
|
||||
for (Int32 i = set.firstOne(); i != -1; i = set.nextOne(i))
|
||||
this->set(i);
|
||||
return *this;
|
||||
}
|
||||
|
||||
#endif // _SPARSE_SET_H_
|
||||
270
mozilla/ef/Compiler/RegisterAllocator/Spilling.cpp
Normal file
270
mozilla/ef/Compiler/RegisterAllocator/Spilling.cpp
Normal file
@@ -0,0 +1,270 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef NEW_LAURENTM_CODE
|
||||
#define INCLUDE_EMITTER
|
||||
#include "CpuInfo.h"
|
||||
#include "Fundamentals.h"
|
||||
#include "ControlNodes.h"
|
||||
#include "Instruction.h"
|
||||
#include "InstructionEmitter.h"
|
||||
#include "Spilling.h"
|
||||
|
||||
|
||||
void Spilling::
|
||||
insertSpillCode(ControlNode** dfsList, Uint32 nNodes)
|
||||
{
|
||||
PRUint32 nVirtualRegisters = vRegManager.count();
|
||||
FastBitSet currentLive(vRegManager.pool, nVirtualRegisters);
|
||||
FastBitSet usedInThisInstruction(vRegManager.pool, nVirtualRegisters);
|
||||
RegisterFifo grNeedLoad(nVirtualRegisters);
|
||||
RegisterFifo fpNeedLoad(nVirtualRegisters);
|
||||
|
||||
for (PRInt32 n = nNodes - 1; n >= 0; n--)
|
||||
{
|
||||
PR_ASSERT(grNeedLoad.empty() & fpNeedLoad.empty());
|
||||
ControlNode& node = *dfsList[n];
|
||||
|
||||
currentLive = node.liveAtEnd;
|
||||
|
||||
PRUint32 nGeneralAlive = 0;
|
||||
PRUint32 nFloatingPointAlive = 0;
|
||||
|
||||
// Get the number of registers alive at the end of this node.
|
||||
for (PRInt32 j = currentLive.firstOne(); j != -1; j = currentLive.nextOne(j))
|
||||
{
|
||||
VirtualRegister& vReg = vRegManager.getVirtualRegister(j);
|
||||
if (vReg.spillInfo.willSpill)
|
||||
{
|
||||
currentLive.clear(j);
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (vReg.getClass())
|
||||
{
|
||||
case vrcInteger:
|
||||
nGeneralAlive++;
|
||||
break;
|
||||
case vrcFloatingPoint:
|
||||
case vrcFixedPoint:
|
||||
nFloatingPointAlive++;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if(node.dfsNum == 8) printf("\n________Begin Node %d________\n", node.dfsNum);
|
||||
|
||||
InstructionList& instructions = node.getInstructions();
|
||||
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i))
|
||||
{
|
||||
Instruction& instruction = instructions.get(i);
|
||||
InstructionUse* useBegin = instruction.getInstructionUseBegin();
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
InstructionUse* usePtr;
|
||||
InstructionDefine* defBegin = instruction.getInstructionDefineBegin();
|
||||
InstructionDefine* defEnd = instruction.getInstructionDefineEnd();
|
||||
InstructionDefine* defPtr;
|
||||
|
||||
// if(node.dfsNum == 8) { printf("\n");
|
||||
// instruction.printPretty(stdout);
|
||||
// printf("\n"); }
|
||||
|
||||
// Handle definitions
|
||||
for (defPtr = defBegin; defPtr < defEnd; defPtr++)
|
||||
if (defPtr->isVirtualRegister())
|
||||
{
|
||||
VirtualRegister& vReg = defPtr->getVirtualRegister();
|
||||
currentLive.clear(vReg.getRegisterIndex());
|
||||
switch (vReg.getClass())
|
||||
{
|
||||
case vrcInteger:
|
||||
nGeneralAlive--;
|
||||
break;
|
||||
case vrcFloatingPoint:
|
||||
case vrcFixedPoint:
|
||||
nFloatingPointAlive--;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for deaths
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isVirtualRegister())
|
||||
{
|
||||
VirtualRegister& vReg = usePtr->getVirtualRegister();
|
||||
if (!currentLive.test(vReg.getRegisterIndex()))
|
||||
// This is the last use of this register.
|
||||
{
|
||||
currentLive.set(vReg.getRegisterIndex());
|
||||
switch (vReg.getClass())
|
||||
{
|
||||
case vrcInteger:
|
||||
nGeneralAlive++;
|
||||
while (/*(nGeneralAlive > NUMBER_OF_GREGISTERS) &&*/ !grNeedLoad.empty())
|
||||
{
|
||||
PRUint32 toLoad = grNeedLoad.get();
|
||||
currentLive.clear(toLoad);
|
||||
nGeneralAlive--;
|
||||
|
||||
VirtualRegister& nReg = vRegManager.getVirtualRegister(toLoad);
|
||||
Instruction& lastUsingInstruction = *nReg.spillInfo.lastUsingInstruction;
|
||||
emitter.emitLoadAfter(*lastUsingInstruction.getPrimitive(), lastUsingInstruction.getLinks().prev,
|
||||
nReg.getAlias(), *nReg.equivalentRegister[vrcStackSlot]);
|
||||
nReg.releaseSelf();
|
||||
}
|
||||
break;
|
||||
case vrcFloatingPoint:
|
||||
case vrcFixedPoint:
|
||||
nFloatingPointAlive++;
|
||||
while (/*(nFloatingPointAlive > NUMBER_OF_FPREGISTERS) &&*/ !fpNeedLoad.empty())
|
||||
{
|
||||
PRUint32 toLoad = fpNeedLoad.get();
|
||||
currentLive.clear(toLoad);
|
||||
nFloatingPointAlive--;
|
||||
|
||||
VirtualRegister& nReg = vRegManager.getVirtualRegister(toLoad);
|
||||
Instruction& lastUsingInstruction = *nReg.spillInfo.lastUsingInstruction;
|
||||
emitter.emitLoadAfter(*lastUsingInstruction.getPrimitive(), lastUsingInstruction.getLinks().prev,
|
||||
nReg.getAlias(), *nReg.equivalentRegister[vrcStackSlot]);
|
||||
nReg.releaseSelf();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle uses
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isVirtualRegister())
|
||||
{
|
||||
VirtualRegister& vReg = usePtr->getVirtualRegister();
|
||||
PRUint32 registerIndex = vReg.getRegisterIndex();
|
||||
|
||||
if (vReg.spillInfo.willSpill) {
|
||||
#if defined(GENERATE_FOR_X86)
|
||||
if (!instruction.switchUseToSpill((usePtr - useBegin), *vReg.equivalentRegister[vrcStackSlot]))
|
||||
#endif
|
||||
{
|
||||
switch (vReg.getClass())
|
||||
{
|
||||
case vrcInteger:
|
||||
if (!grNeedLoad.test(registerIndex))
|
||||
{
|
||||
grNeedLoad.put(registerIndex);
|
||||
VirtualRegister& alias = vRegManager.newVirtualRegister(vrcInteger);
|
||||
if (vReg.isPreColored())
|
||||
alias.preColorRegister(vReg.getPreColor());
|
||||
/* if (vReg.hasSpecialInterference) {
|
||||
alias.specialInterference.sizeTo(NUMBER_OF_REGISTERS);
|
||||
alias.specialInterference = vReg.specialInterference;
|
||||
alias.hasSpecialInterference = true;
|
||||
} */
|
||||
vReg.setAlias(alias);
|
||||
vReg.retainSelf();
|
||||
}
|
||||
break;
|
||||
case vrcFloatingPoint:
|
||||
case vrcFixedPoint:
|
||||
if (!fpNeedLoad.test(registerIndex))
|
||||
{
|
||||
fpNeedLoad.put(registerIndex);
|
||||
VirtualRegister& alias = vRegManager.newVirtualRegister(vReg.getClass());
|
||||
if (vReg.isPreColored())
|
||||
alias.preColorRegister(vReg.getPreColor());
|
||||
/*if (vReg.hasSpecialInterference) {
|
||||
alias.specialInterference.sizeTo(NUMBER_OF_REGISTERS);
|
||||
alias.specialInterference = vReg.specialInterference;
|
||||
alias.hasSpecialInterference = true;
|
||||
} */
|
||||
vReg.setAlias(alias);
|
||||
vReg.retainSelf();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
usePtr->getVirtualRegisterPtr().initialize(vReg.getAlias());
|
||||
usedInThisInstruction.set(registerIndex);
|
||||
vReg.spillInfo.lastUsingInstruction = &instruction;
|
||||
}
|
||||
currentLive.clear(registerIndex);
|
||||
} else { // will not spill
|
||||
currentLive.set(registerIndex);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle definitions
|
||||
for (defPtr = defBegin; defPtr < defEnd; defPtr++)
|
||||
if (defPtr->isVirtualRegister())
|
||||
{
|
||||
VirtualRegister& vReg = defPtr->getVirtualRegister();
|
||||
|
||||
if (vReg.spillInfo.willSpill)
|
||||
#if defined(GENERATE_FOR_X86)
|
||||
if (!instruction.switchDefineToSpill((defPtr - defBegin), *vReg.equivalentRegister[vrcStackSlot]))
|
||||
#endif
|
||||
{
|
||||
if (usedInThisInstruction.test(vReg.getRegisterIndex()))
|
||||
// this virtualRegister was used in this instruction and is also defined. We need to move
|
||||
// this virtual register to its alias first and then save it to memory.
|
||||
{
|
||||
emitter.emitStoreAfter(*instruction.getPrimitive(), &instruction.getLinks(),
|
||||
vReg.getAlias(), *vReg.equivalentRegister[vrcStackSlot]);
|
||||
defPtr->getVirtualRegisterPtr().initialize(vReg.getAlias());
|
||||
}
|
||||
else
|
||||
{
|
||||
emitter.emitStoreAfter(*instruction.getPrimitive(), &instruction.getLinks(),
|
||||
vReg, *vReg.equivalentRegister[vrcStackSlot]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
while (!grNeedLoad.empty())
|
||||
{
|
||||
PRUint32 nl = grNeedLoad.get();
|
||||
VirtualRegister& nlReg = vRegManager.getVirtualRegister(nl);
|
||||
Instruction& lastUse = *nlReg.spillInfo.lastUsingInstruction;
|
||||
|
||||
emitter.emitLoadAfter(*lastUse.getPrimitive(), lastUse.getLinks().prev,
|
||||
nlReg.getAlias(), *nlReg.equivalentRegister[vrcStackSlot]);
|
||||
nlReg.releaseSelf();
|
||||
}
|
||||
while (!fpNeedLoad.empty())
|
||||
{
|
||||
PRUint32 nl = fpNeedLoad.get();
|
||||
VirtualRegister& nlReg = vRegManager.getVirtualRegister(nl);
|
||||
Instruction& lastUse = *nlReg.spillInfo.lastUsingInstruction;
|
||||
|
||||
emitter.emitLoadAfter(*lastUse.getPrimitive(), lastUse.getLinks().prev,
|
||||
nlReg.getAlias(), *nlReg.equivalentRegister[vrcStackSlot]);
|
||||
nlReg.releaseSelf();
|
||||
}
|
||||
|
||||
// if(node.dfsNum == 8) printf("\n________End Node %d________\n", node.dfsNum);
|
||||
|
||||
}
|
||||
}
|
||||
#endif
|
||||
269
mozilla/ef/Compiler/RegisterAllocator/Spilling.h
Normal file
269
mozilla/ef/Compiler/RegisterAllocator/Spilling.h
Normal file
@@ -0,0 +1,269 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SPILLING_H_
|
||||
#define _SPILLING_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include <string.h>
|
||||
#include "RegisterAllocator.h"
|
||||
#include "RegisterAllocatorTools.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "ControlNodes.h"
|
||||
#include "Instruction.h"
|
||||
#include "SparseSet.h"
|
||||
|
||||
template <class RegisterPressure>
|
||||
class Spilling
|
||||
{
|
||||
private:
|
||||
static void insertStoreAfter(Instruction& instruction, RegisterName name);
|
||||
static void insertLoadBefore(Instruction& instruction, RegisterName name);
|
||||
|
||||
public:
|
||||
static void calculateSpillCosts(RegisterAllocator& registerAllocator);
|
||||
static void insertSpillCode(RegisterAllocator& registerAllocator);
|
||||
};
|
||||
|
||||
struct SpillCost
|
||||
{
|
||||
double loads;
|
||||
double stores;
|
||||
double copies;
|
||||
double cost;
|
||||
bool infinite;
|
||||
};
|
||||
|
||||
template <class RegisterPressure>
|
||||
void Spilling<RegisterPressure>::insertSpillCode(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
Uint32 rangeCount = registerAllocator.rangeCount;
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
|
||||
Pool& pool = registerAllocator.pool;
|
||||
SparseSet currentLive(pool, rangeCount);
|
||||
SparseSet needLoad(pool, rangeCount);
|
||||
SparseSet mustSpill(pool, rangeCount);
|
||||
SparseSet& willSpill = *registerAllocator.willSpill;
|
||||
|
||||
ControlGraph& controlGraph = registerAllocator.controlGraph;
|
||||
RegisterPressure::Set* liveOut = registerAllocator.liveness.liveOut;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
|
||||
needLoad.clear();
|
||||
currentLive = liveOut[n];
|
||||
mustSpill = currentLive;
|
||||
|
||||
InstructionList& instructions = nodes[n]->getInstructions();
|
||||
for (InstructionList::iterator i = instructions.end(); !instructions.done(i);) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
i = instructions.retreat(i);
|
||||
|
||||
InstructionUse* useBegin = instruction.getInstructionUseBegin();
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
InstructionUse* usePtr;
|
||||
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
InstructionDefine* definePtr;
|
||||
|
||||
bool foundLiveDefine = false;
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister()) {
|
||||
if (currentLive.test(name2range[definePtr->getRegisterName()])) {
|
||||
foundLiveDefine = true;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
foundLiveDefine = true;
|
||||
break;
|
||||
}
|
||||
if (defineBegin != defineEnd && !foundLiveDefine) {
|
||||
fprintf(stderr, "!!! Removed instruction because it was only defining unused registers !!!\n");
|
||||
instruction.remove();
|
||||
}
|
||||
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister()) {
|
||||
RegisterName range = name2range[definePtr->getRegisterName()];
|
||||
#ifdef DEBUG
|
||||
if (needLoad.test(range))
|
||||
if (!mustSpill.test(range) && registerAllocator.spillCost[range].infinite && willSpill.test(range)) {
|
||||
fprintf(stderr, "Tried to spill a register with infinite spill cost\n");
|
||||
abort();
|
||||
}
|
||||
#endif // DEBUG
|
||||
if (willSpill.test(range))
|
||||
insertStoreAfter(instruction, range);
|
||||
|
||||
needLoad.clear(range);
|
||||
}
|
||||
|
||||
if (instruction.getFlags() & ifCopy)
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
RegisterName range = name2range[usePtr->getRegisterName()];
|
||||
if (!currentLive.test(range))
|
||||
for (SparseSet::iterator r = needLoad.begin(); !needLoad.done(r); r = needLoad.advance(r)) {
|
||||
RegisterName load = RegisterName(needLoad.get(r));
|
||||
if (willSpill.test(load))
|
||||
insertLoadBefore(instruction, load);
|
||||
mustSpill.set(load);
|
||||
}
|
||||
needLoad.clear();
|
||||
}
|
||||
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
currentLive.clear(name2range[definePtr->getRegisterName()]);
|
||||
|
||||
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
RegisterName range = name2range[usePtr->getRegisterName()];
|
||||
currentLive.set(range);
|
||||
needLoad.set(range);
|
||||
}
|
||||
}
|
||||
|
||||
for (SparseSet::iterator l = needLoad.begin(); !needLoad.done(l); l = needLoad.advance(l)) {
|
||||
RegisterName load = RegisterName(needLoad.get(l));
|
||||
if (willSpill.test(load))
|
||||
insertLoadBefore(instructions.first(), load);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
void Spilling<RegisterPressure>::insertLoadBefore(Instruction& /*instruction*/, RegisterName name)
|
||||
{
|
||||
fprintf(stdout, "will insert load for range %d\n", name);
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
void Spilling<RegisterPressure>::insertStoreAfter(Instruction& /*instruction*/, RegisterName name)
|
||||
{
|
||||
fprintf(stdout, "will insert store for range %d\n", name);
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
void Spilling<RegisterPressure>::calculateSpillCosts(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
Uint32 rangeCount = registerAllocator.rangeCount;
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
|
||||
Pool& pool = registerAllocator.pool;
|
||||
SparseSet live(pool, rangeCount);
|
||||
SparseSet needLoad(pool, rangeCount);
|
||||
SparseSet mustSpill(pool, rangeCount);
|
||||
|
||||
SparseSet alreadyStored(pool, rangeCount); // FIX: should get this from previous spilling.
|
||||
|
||||
SpillCost* cost = new SpillCost[rangeCount];
|
||||
memset(cost, '\0', rangeCount * sizeof(SpillCost));
|
||||
|
||||
ControlGraph& controlGraph = registerAllocator.controlGraph;
|
||||
RegisterPressure::Set* liveOut = registerAllocator.liveness.liveOut;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
ControlNode& node = *nodes[n];
|
||||
|
||||
double weight = doLog10(node.loopDepth);
|
||||
|
||||
needLoad.clear();
|
||||
live = liveOut[n];
|
||||
mustSpill = live;
|
||||
|
||||
InstructionList& instructions = nodes[n]->getInstructions();
|
||||
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
InstructionUse* useBegin = instruction.getInstructionUseBegin();
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
InstructionUse* usePtr;
|
||||
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
InstructionDefine* definePtr;
|
||||
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister()) {
|
||||
RegisterName range = name2range[definePtr->getRegisterName()];
|
||||
|
||||
if (needLoad.test(range))
|
||||
if (!mustSpill.test(range))
|
||||
cost[range].infinite = true;
|
||||
|
||||
if ((false /* !rematerializable(range) */ || !needLoad.test(range)) && !alreadyStored.test(range))
|
||||
cost[range].stores += weight;
|
||||
|
||||
needLoad.clear(range);
|
||||
}
|
||||
|
||||
if (instruction.getFlags() & ifCopy)
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister())
|
||||
if (!live.test(name2range[usePtr->getRegisterName()])) {
|
||||
for (SparseSet::iterator l = needLoad.begin(); !needLoad.done(l); l = needLoad.advance(l)) {
|
||||
Uint32 range = needLoad.get(l);
|
||||
cost[range].loads += weight;
|
||||
mustSpill.set(range);
|
||||
}
|
||||
needLoad.clear();
|
||||
}
|
||||
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
live.clear(name2range[definePtr->getRegisterName()]);
|
||||
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
RegisterName range = name2range[usePtr->getRegisterName()];
|
||||
|
||||
live.set(range);
|
||||
needLoad.set(range);
|
||||
}
|
||||
|
||||
if (instruction.getFlags() & ifCopy) {
|
||||
assert(useBegin != useEnd && useBegin[0].isRegister());
|
||||
assert(defineBegin != defineEnd && defineBegin[0].isRegister());
|
||||
|
||||
RegisterName source = name2range[useBegin[0].getRegisterName()];
|
||||
RegisterName destination = name2range[defineBegin[0].getRegisterName()];
|
||||
|
||||
cost[source].copies += weight;
|
||||
cost[destination].copies += weight;
|
||||
}
|
||||
}
|
||||
|
||||
for (SparseSet::iterator s = needLoad.begin(); !needLoad.done(s); s = needLoad.advance(s))
|
||||
cost[needLoad.get(s)].loads += weight;
|
||||
}
|
||||
|
||||
for (Uint32 r = 0; r < rangeCount; r++) {
|
||||
SpillCost& c = cost[r];
|
||||
c.cost = 2 * (c.loads + c.stores) - c.copies;
|
||||
}
|
||||
|
||||
registerAllocator.spillCost = cost;
|
||||
}
|
||||
|
||||
#endif // _SPILLING_H_
|
||||
239
mozilla/ef/Compiler/RegisterAllocator/Splits.h
Normal file
239
mozilla/ef/Compiler/RegisterAllocator/Splits.h
Normal file
@@ -0,0 +1,239 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _SPLITS_H_
|
||||
#define _SPLITS_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include <string.h>
|
||||
#include "Pool.h"
|
||||
#include "ControlGraph.h"
|
||||
#include "ControlNodes.h"
|
||||
#include "Instruction.h"
|
||||
#include "RegisterAllocator.h"
|
||||
#include "RegisterAllocatorTools.h"
|
||||
|
||||
UT_EXTERN_LOG_MODULE(RegAlloc);
|
||||
|
||||
template <class RegisterPressure>
|
||||
struct Splits
|
||||
{
|
||||
static void calculateSplitCosts(RegisterAllocator& registerAllocator);
|
||||
static bool findSplit(RegisterAllocator& registerAllocator, RegisterName* color, RegisterName range);
|
||||
static void insertSplitCode(RegisterAllocator& registerAllocator);
|
||||
};
|
||||
|
||||
struct SplitCost
|
||||
{
|
||||
double loads;
|
||||
double stores;
|
||||
};
|
||||
|
||||
template <class RegisterPressure>
|
||||
void Splits<RegisterPressure>::insertSplitCode(RegisterAllocator& /*registerAllocator*/)
|
||||
{
|
||||
// FIX
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
bool Splits<RegisterPressure>::findSplit(RegisterAllocator& registerAllocator, RegisterName* color, RegisterName range)
|
||||
{
|
||||
Pool& pool = registerAllocator.pool;
|
||||
NameLinkedList** neighborsWithColor = new(pool) NameLinkedList*[6]; // FIX
|
||||
memset(neighborsWithColor, '\0', 6 * sizeof(NameLinkedList*));
|
||||
|
||||
InterferenceGraph<RegisterPressure>& iGraph = registerAllocator.iGraph;
|
||||
|
||||
for (InterferenceVector* vector = iGraph.getInterferenceVector(range); vector != NULL; vector = vector->next)
|
||||
for (Int32 i = vector->count - 1; i >=0; --i) {
|
||||
RegisterName neighbor = vector->neighbors[i];
|
||||
RegisterName c = color[neighbor];
|
||||
|
||||
if (c < 6) { // FIX
|
||||
NameLinkedList* node = new(pool) NameLinkedList();
|
||||
node->name = neighbor;
|
||||
node->next = neighborsWithColor[c];
|
||||
neighborsWithColor[c] = node;
|
||||
}
|
||||
}
|
||||
|
||||
bool splitAroundName = true;
|
||||
|
||||
LiveRangeGraph<RegisterPressure>& lGraph = registerAllocator.lGraph;
|
||||
RegisterName bestColor = RegisterName(6); // FIX
|
||||
double bestCost = registerAllocator.spillCost[range].cost;
|
||||
SplitCost* splitCost = registerAllocator.splitCost;
|
||||
|
||||
for (RegisterName i = RegisterName(0); i < 6; i = RegisterName(i + 1)) { // FIX
|
||||
|
||||
double splitAroundNameCost = 0.0;
|
||||
bool canSplitAroundName = true;
|
||||
|
||||
SplitCost& sCost = splitCost[range];
|
||||
double addedCost = 2.0 * (sCost.stores + sCost.loads);
|
||||
|
||||
for (NameLinkedList* node = neighborsWithColor[i]; node != NULL; node = node->next) {
|
||||
RegisterName neighbor = node->name;
|
||||
if (lGraph.haveEdge(neighbor, range)) {
|
||||
canSplitAroundName = false;
|
||||
break;
|
||||
} else
|
||||
splitAroundNameCost += addedCost;
|
||||
}
|
||||
if (canSplitAroundName && splitAroundNameCost < bestCost) {
|
||||
bestCost = splitAroundNameCost;
|
||||
bestColor = i;
|
||||
splitAroundName = true;
|
||||
}
|
||||
|
||||
double splitAroundColorCost = 0.0;
|
||||
bool canSplitAroundColor = true;
|
||||
|
||||
for (NameLinkedList* node = neighborsWithColor[i]; node != NULL; node = node->next) {
|
||||
RegisterName neighbor = node->name;
|
||||
if (lGraph.haveEdge(range, neighbor)) {
|
||||
canSplitAroundColor = false;
|
||||
break;
|
||||
} else {
|
||||
SplitCost& sCost = splitCost[neighbor];
|
||||
double addedCost = 2.0 * (sCost.stores + sCost.loads);
|
||||
splitAroundColorCost += addedCost;
|
||||
}
|
||||
}
|
||||
if (canSplitAroundColor && splitAroundColorCost < bestCost) {
|
||||
bestCost = splitAroundColorCost;
|
||||
bestColor = i;
|
||||
splitAroundName = false;
|
||||
}
|
||||
}
|
||||
if (bestColor < RegisterName(6)) {
|
||||
color[range] = bestColor;
|
||||
registerAllocator.splitFound = true;
|
||||
|
||||
NameLinkedList** splitAround = registerAllocator.splitAround;
|
||||
|
||||
if (splitAroundName)
|
||||
for (NameLinkedList* node = neighborsWithColor[bestColor]; node != NULL; node = node->next) {
|
||||
NameLinkedList* newNode = new(pool) NameLinkedList();
|
||||
newNode->name = node->name;
|
||||
newNode->next = splitAround[range];
|
||||
splitAround[range] = newNode;
|
||||
}
|
||||
else
|
||||
for (NameLinkedList* node = neighborsWithColor[bestColor]; node != NULL; node = node->next) {
|
||||
NameLinkedList* newNode = new(pool) NameLinkedList();
|
||||
RegisterName neighbor = node->name;
|
||||
newNode->name = range;
|
||||
newNode->next = splitAround[neighbor];
|
||||
splitAround[neighbor] = newNode;
|
||||
}
|
||||
|
||||
trespass("Found a split");
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <class RegisterPressure>
|
||||
void Splits<RegisterPressure>::calculateSplitCosts(RegisterAllocator& registerAllocator)
|
||||
{
|
||||
Pool& pool = registerAllocator.pool;
|
||||
Uint32 rangeCount = registerAllocator.rangeCount;
|
||||
RegisterName* name2range = registerAllocator.name2range;
|
||||
|
||||
SplitCost* splitCost = new(pool) SplitCost[rangeCount];
|
||||
memset(splitCost, '\0', rangeCount * sizeof(SplitCost));
|
||||
|
||||
SparseSet live(pool, rangeCount);
|
||||
RegisterPressure::Set* liveIn = registerAllocator.liveness.liveIn;
|
||||
RegisterPressure::Set* liveOut = registerAllocator.liveness.liveOut;
|
||||
|
||||
ControlGraph& controlGraph = registerAllocator.controlGraph;
|
||||
ControlNode** nodes = controlGraph.dfsList;
|
||||
Uint32 nNodes = controlGraph.nNodes;
|
||||
|
||||
for (Uint32 n = 0; n < nNodes; n++) {
|
||||
ControlNode& node = *nodes[n];
|
||||
double weight = doLog10(node.loopDepth);
|
||||
|
||||
live = liveOut[n];
|
||||
|
||||
ControlEdge* successorsEnd = node.getSuccessorsEnd();
|
||||
for (ControlEdge* successorsPtr = node.getSuccessorsBegin(); successorsPtr < successorsEnd; successorsPtr++) {
|
||||
ControlNode& successor = successorsPtr->getTarget();
|
||||
|
||||
if (successor.getControlKind() != ckEnd) {
|
||||
RegisterPressure::Set& successorLiveIn = liveIn[successor.dfsNum];
|
||||
|
||||
for (SparseSet::iterator i = live.begin(); !live.done(i); i = live.advance(i)) {
|
||||
RegisterName name = RegisterName(live.get(i));
|
||||
if (!successorLiveIn.test(name))
|
||||
splitCost[name].loads += doLog10(successor.loopDepth);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
InstructionList& instructions = node.getInstructions();
|
||||
for (InstructionList::iterator i = instructions.end(); !instructions.done(i); i = instructions.retreat(i)) {
|
||||
Instruction& instruction = instructions.get(i);
|
||||
|
||||
InstructionUse* useBegin = instruction.getInstructionUseBegin();
|
||||
InstructionUse* useEnd = instruction.getInstructionUseEnd();
|
||||
InstructionUse* usePtr;
|
||||
InstructionDefine* defineBegin = instruction.getInstructionDefineBegin();
|
||||
InstructionDefine* defineEnd = instruction.getInstructionDefineEnd();
|
||||
InstructionDefine* definePtr;
|
||||
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
splitCost[name2range[definePtr->getRegisterName()]].stores += weight;
|
||||
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister()) {
|
||||
RegisterName range = name2range[usePtr->getRegisterName()];
|
||||
if (!live.test(range)) {
|
||||
if (&instruction != &instructions.last())
|
||||
splitCost[range].loads += weight;
|
||||
else {
|
||||
ControlEdge* successorsEnd = node.getSuccessorsEnd();
|
||||
for (ControlEdge* successorsPtr = node.getSuccessorsBegin(); successorsPtr < successorsEnd; successorsPtr++)
|
||||
splitCost[range].loads += doLog10(successorsPtr->getTarget().loopDepth);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (definePtr = defineBegin; definePtr < defineEnd; definePtr++)
|
||||
if (definePtr->isRegister())
|
||||
live.clear(name2range[definePtr->getRegisterName()]);
|
||||
|
||||
for (usePtr = useBegin; usePtr < useEnd; usePtr++)
|
||||
if (usePtr->isRegister())
|
||||
live.set(name2range[usePtr->getRegisterName()]);
|
||||
}
|
||||
}
|
||||
|
||||
NameLinkedList** splitAround = new(pool) NameLinkedList*[rangeCount];
|
||||
memset(splitAround, '\0', rangeCount * sizeof(NameLinkedList*));
|
||||
registerAllocator.splitAround = splitAround;
|
||||
|
||||
registerAllocator.splitCost = splitCost;
|
||||
registerAllocator.splitFound = false;
|
||||
}
|
||||
|
||||
#endif // _SPLITS_H_
|
||||
186
mozilla/ef/Compiler/RegisterAllocator/Timer.cpp
Normal file
186
mozilla/ef/Compiler/RegisterAllocator/Timer.cpp
Normal file
@@ -0,0 +1,186 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "HashTable.h"
|
||||
#include "Timer.h"
|
||||
#include "Pool.h"
|
||||
|
||||
static Pool pool; // Pool for the Timer class.
|
||||
static HashTable<TimerEntry*> timerEntries(pool); // Timers hashtable.
|
||||
|
||||
const nTimersInABlock = 128; // Number of timers in a block.
|
||||
static PRTime *timers = new(pool) PRTime[nTimersInABlock]; // A block of timers.
|
||||
static Uint8 nextTimer = 0; // nextAvailableTimer.
|
||||
|
||||
//
|
||||
// Calibrate the call to PR_Now().
|
||||
//
|
||||
static PRTime calibrate()
|
||||
{
|
||||
PRTime t = PR_Now();
|
||||
PRTime& a = *new(pool) PRTime();
|
||||
|
||||
// Call 10 times the PR_Now() function.
|
||||
a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now();
|
||||
a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now(); a = PR_Now();
|
||||
t = (PR_Now() - t + 9) / 10;
|
||||
|
||||
return t;
|
||||
}
|
||||
|
||||
static PRTime adjust = calibrate();
|
||||
|
||||
//
|
||||
// Return the named timer..
|
||||
//
|
||||
TimerEntry& Timer::getTimerEntry(const char* name)
|
||||
{
|
||||
if (!timerEntries.exists(name)) {
|
||||
TimerEntry* newEntry = new(pool) TimerEntry();
|
||||
newEntry->accumulator = 0;
|
||||
newEntry->running = false;
|
||||
timerEntries.add(name, newEntry);
|
||||
}
|
||||
|
||||
return *timerEntries[name];
|
||||
}
|
||||
|
||||
//
|
||||
// Return a reference to a new timer.
|
||||
//
|
||||
PRTime& Timer::getNewTimer()
|
||||
{
|
||||
if (nextTimer >= nTimersInABlock) {
|
||||
timers = new(pool) PRTime[nTimersInABlock];
|
||||
nextTimer = 0;
|
||||
}
|
||||
return timers[nextTimer++];
|
||||
}
|
||||
|
||||
static Uint32 timersAreFrozen = 0;
|
||||
|
||||
//
|
||||
// Start the named timer.
|
||||
//
|
||||
void Timer::start(const char* name)
|
||||
{
|
||||
if (timersAreFrozen)
|
||||
return;
|
||||
|
||||
freezeTimers();
|
||||
|
||||
TimerEntry& timer = getTimerEntry(name);
|
||||
PR_ASSERT(!timer.running);
|
||||
|
||||
timer.accumulator = 0;
|
||||
timer.running = true;
|
||||
timer.done = false;
|
||||
|
||||
unfreezeTimers();
|
||||
}
|
||||
|
||||
//
|
||||
// Stop the named timer.
|
||||
//
|
||||
void Timer::stop(const char* name)
|
||||
{
|
||||
if (timersAreFrozen)
|
||||
return;
|
||||
|
||||
freezeTimers();
|
||||
|
||||
TimerEntry& timer = getTimerEntry(name);
|
||||
PR_ASSERT(timer.running);
|
||||
timer.running = false;
|
||||
timer.done = true;
|
||||
|
||||
unfreezeTimers();
|
||||
}
|
||||
|
||||
//
|
||||
// Freeze all the running timers.
|
||||
//
|
||||
void Timer::freezeTimers()
|
||||
{
|
||||
PRTime when = PR_Now() - adjust;
|
||||
|
||||
if (timersAreFrozen == 0) {
|
||||
Vector<TimerEntry*> entries = timerEntries;
|
||||
Uint32 count = entries.size();
|
||||
|
||||
for (Uint32 i = 0; i < count; i++) {
|
||||
TimerEntry& entry = *entries[i];
|
||||
if (entry.running) {
|
||||
entry.accumulator += (when - *entry.startTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
timersAreFrozen++;
|
||||
}
|
||||
|
||||
//
|
||||
// Unfreeze all the running timers.
|
||||
//
|
||||
void Timer::unfreezeTimers()
|
||||
{
|
||||
PR_ASSERT(timersAreFrozen != 0);
|
||||
timersAreFrozen--;
|
||||
|
||||
if (timersAreFrozen == 0) {
|
||||
Vector<TimerEntry *> entries = timerEntries;
|
||||
Uint32 count = entries.size();
|
||||
|
||||
PRTime& newStart = getNewTimer();
|
||||
|
||||
for (Uint32 i = 0; i < count; i++) {
|
||||
TimerEntry& entry = *entries[i];
|
||||
if (entry.running) {
|
||||
entry.startTime = &newStart;
|
||||
}
|
||||
}
|
||||
|
||||
newStart = PR_Now();
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Print the named timer in the file f.
|
||||
//
|
||||
void Timer::print(FILE* f, const char *name)
|
||||
{
|
||||
if (timersAreFrozen)
|
||||
return;
|
||||
|
||||
freezeTimers();
|
||||
|
||||
TimerEntry& timer = getTimerEntry(name);
|
||||
|
||||
PR_ASSERT(timer.done);
|
||||
PRTime elapsed = timer.accumulator;
|
||||
|
||||
if (elapsed >> 32) {
|
||||
fprintf(f, "[timer %s out of range]\n", name);
|
||||
} else {
|
||||
fprintf(f, "[%dus in %s]\n", Uint32(elapsed), name);
|
||||
}
|
||||
fflush(f);
|
||||
|
||||
unfreezeTimers();
|
||||
}
|
||||
|
||||
80
mozilla/ef/Compiler/RegisterAllocator/Timer.h
Normal file
80
mozilla/ef/Compiler/RegisterAllocator/Timer.h
Normal file
@@ -0,0 +1,80 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _TIMER_H_
|
||||
#define _TIMER_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "HashTable.h"
|
||||
#include "prtime.h"
|
||||
|
||||
//
|
||||
// Naming convention:
|
||||
// As the class Timer contains only static methods, the timer's name should start with the
|
||||
// module name. Otherwise starting 2 timers with the same name will assert.
|
||||
//
|
||||
|
||||
#ifndef NO_TIMER
|
||||
|
||||
struct TimerEntry
|
||||
{
|
||||
PRTime *startTime; // Current time when we start the timer.
|
||||
PRTime accumulator; // Time spent in this timer.
|
||||
bool running; // True if the timer is running.
|
||||
bool done; // True if the timer was running and was stopped.
|
||||
};
|
||||
|
||||
class Timer
|
||||
{
|
||||
private:
|
||||
|
||||
// Return the named timer.
|
||||
static TimerEntry& getTimerEntry(const char* name);
|
||||
// Return a reference to a new Timer.
|
||||
static PRTime& getNewTimer();
|
||||
|
||||
public:
|
||||
|
||||
// Start the timer.
|
||||
static void start(const char* name);
|
||||
// Stop the timer.
|
||||
static void stop(const char* name);
|
||||
// Freeze all the running timers.
|
||||
static void freezeTimers();
|
||||
// Unfreeze all the running timers.
|
||||
static void unfreezeTimers();
|
||||
// Print the timer.
|
||||
static void print(FILE* f, const char *name);
|
||||
};
|
||||
|
||||
inline void startTimer(const char* name) {Timer::start(name);}
|
||||
inline void stopTimer(const char* name) {Timer::stop(name); Timer::print(stdout, name);}
|
||||
#define START_TIMER_SAFE Timer::freezeTimers();
|
||||
#define END_TIMER_SAFE Timer::unfreezeTimers();
|
||||
#define TIMER_SAFE(x) START_TIMER_SAFE x; END_TIMER_SAFE
|
||||
|
||||
#else /* NO_TIMER */
|
||||
|
||||
inline void startTimer(const char* /*name*/) {}
|
||||
inline void stopTimer(const char* /*name*/) {}
|
||||
#define START_TIMER_SAFE
|
||||
#define END_TIMER_SAFE
|
||||
#define TIMER_SAFE(x) x;
|
||||
|
||||
#endif /* NO_TIMER */
|
||||
#endif /* _TIMER_H_ */
|
||||
40
mozilla/ef/Compiler/RegisterAllocator/VirtualRegister.cpp
Normal file
40
mozilla/ef/Compiler/RegisterAllocator/VirtualRegister.cpp
Normal file
@@ -0,0 +1,40 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "VirtualRegister.h"
|
||||
#include "Instruction.h"
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// VirtualRegister -
|
||||
|
||||
#ifdef MANUAL_TEMPLATES
|
||||
template class IndexedPool<VirtualRegister>;
|
||||
#endif
|
||||
|
||||
// Set the defining instruction.
|
||||
//
|
||||
void VirtualRegister::setDefiningInstruction(Instruction& instruction)
|
||||
{
|
||||
if (definingInstruction != NULL) {
|
||||
if ((instruction.getFlags() & ifCopy) && (definingInstruction->getFlags() & ifPhiNode))
|
||||
return;
|
||||
}
|
||||
definingInstruction = &instruction;
|
||||
}
|
||||
|
||||
116
mozilla/ef/Compiler/RegisterAllocator/VirtualRegister.h
Normal file
116
mozilla/ef/Compiler/RegisterAllocator/VirtualRegister.h
Normal file
@@ -0,0 +1,116 @@
|
||||
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape Public License
|
||||
* Version 1.0 (the "NPL"); you may not use this file except in
|
||||
* compliance with the NPL. You may obtain a copy of the NPL at
|
||||
* http://www.mozilla.org/NPL/
|
||||
*
|
||||
* Software distributed under the NPL is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
|
||||
* for the specific language governing rights and limitations under the
|
||||
* NPL.
|
||||
*
|
||||
* The Initial Developer of this code under the NPL is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1998 Netscape Communications Corporation. All Rights
|
||||
* Reserved.
|
||||
*/
|
||||
|
||||
#ifndef _VIRTUAL_REGISTER_H_
|
||||
#define _VIRTUAL_REGISTER_H_
|
||||
|
||||
#include "Fundamentals.h"
|
||||
#include "IndexedPool.h"
|
||||
#include <string.h>
|
||||
|
||||
#include "RegisterTypes.h"
|
||||
#include "RegisterClass.h"
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// VirtualRegister - 24b
|
||||
|
||||
class Instruction;
|
||||
|
||||
class VirtualRegister : public IndexedObject<VirtualRegister>
|
||||
{
|
||||
public:
|
||||
|
||||
Instruction* definingInstruction; // Instruction defining this VR.
|
||||
|
||||
// Initialize a VR of the given classKind.
|
||||
VirtualRegister(RegisterClassKind /*classKind*/) : definingInstruction(NULL) {}
|
||||
|
||||
// Return the defining instruction for this VR.
|
||||
Instruction* getDefiningInstruction() const {return definingInstruction;}
|
||||
// Set the defining instruction.
|
||||
void setDefiningInstruction(Instruction& insn);
|
||||
};
|
||||
|
||||
// Return true if the VirtualRegisters are equals. The only way 2 VRs can be equal is if
|
||||
// they have the same index. If they have the same index then they are at the same
|
||||
// address in the indexed pool.
|
||||
//
|
||||
inline bool operator == (const VirtualRegister& regA, const VirtualRegister& regB) {return ®A == ®B;}
|
||||
|
||||
//------------------------------------------------------------------------------
|
||||
// VirtualRegisterManager -
|
||||
|
||||
struct PreColoredRegister
|
||||
{
|
||||
RegisterID id;
|
||||
RegisterName color;
|
||||
};
|
||||
|
||||
class VirtualRegisterManager
|
||||
{
|
||||
private:
|
||||
|
||||
IndexedPool<VirtualRegister> registerPool;
|
||||
PreColoredRegister machineRegister[6];
|
||||
|
||||
public:
|
||||
VirtualRegisterManager()
|
||||
{
|
||||
for (Uint32 i = 0; i < 6; i++)
|
||||
machineRegister[i].id = invalidID;
|
||||
}
|
||||
|
||||
// Return the VirtualRegister at the given index.
|
||||
VirtualRegister& getVirtualRegister(RegisterName name) const {return registerPool.get(name);}
|
||||
|
||||
// Return a new VirtualRegister.
|
||||
RegisterID newVirtualRegister(RegisterClassKind classKind)
|
||||
{
|
||||
VirtualRegister& vReg = *new(registerPool) VirtualRegister(classKind);
|
||||
RegisterID rid;
|
||||
|
||||
setName(rid, RegisterName(vReg.getIndex()));
|
||||
setClass(rid, classKind);
|
||||
return rid;
|
||||
}
|
||||
|
||||
RegisterID newMachineRegister(RegisterName name, RegisterClassKind classKind)
|
||||
{
|
||||
RegisterID rid = machineRegister[name].id;
|
||||
|
||||
if (rid == invalidID) {
|
||||
rid = newVirtualRegister(classKind);
|
||||
DEBUG_ONLY(setMachineRegister(rid));
|
||||
machineRegister[name].id = rid;
|
||||
machineRegister[name].color = name;
|
||||
}
|
||||
|
||||
return rid;
|
||||
}
|
||||
|
||||
PreColoredRegister* getMachineRegistersBegin() const {return (PreColoredRegister*) machineRegister;} // FIX
|
||||
PreColoredRegister* getMachineRegistersEnd() const {return (PreColoredRegister*) &machineRegister[6];} // FIX
|
||||
|
||||
// Return the VirtualRegister universe size.
|
||||
Uint32 getSize() {return registerPool.getSize();}
|
||||
|
||||
void setSize(Uint32 size) {registerPool.setSize(size);}
|
||||
};
|
||||
|
||||
#endif // _VIRTUAL_REGISTER_H_
|
||||
@@ -1,46 +0,0 @@
|
||||
<html>
|
||||
<!--
|
||||
- The contents of this file are subject to the Netscape 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/NPL/
|
||||
-
|
||||
- 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 Netscape are
|
||||
- Copyright (C) 1998-1999 Netscape Communications Corporation. All
|
||||
- Rights Reserved.
|
||||
-
|
||||
- Contributor(s):
|
||||
- Norris Boyd
|
||||
-
|
||||
- Alternatively, the contents of this file may be used under the
|
||||
- terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
- deleting the provisions above and replace 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 NPL or the GPL.
|
||||
-->
|
||||
<body>
|
||||
<h1>
|
||||
<span CLASS=LXRSHORTDESC>
|
||||
Rhino: JavaScript in Java<p>
|
||||
</span>
|
||||
</h1>
|
||||
<span CLASS=LXRLONGDESC>
|
||||
Rhino is an implementation of JavaScript in Java. Documentation can be found
|
||||
<a href="http://www.mozilla.org/rhino/index.html">here</a>.
|
||||
</span>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,22 +0,0 @@
|
||||
apiClasses=\
|
||||
src/org/mozilla/javascript/ClassCache.java,\
|
||||
src/org/mozilla/javascript/ClassDefinitionException.java,\
|
||||
src/org/mozilla/javascript/ClassShutter.java,\
|
||||
src/org/mozilla/javascript/Context.java,\
|
||||
src/org/mozilla/javascript/ContextListener.java,\
|
||||
src/org/mozilla/javascript/EcmaError.java,\
|
||||
src/org/mozilla/javascript/ErrorReporter.java,\
|
||||
src/org/mozilla/javascript/Function.java,\
|
||||
src/org/mozilla/javascript/FunctionObject.java,\
|
||||
src/org/mozilla/javascript/ImporterTopLevel.java,\
|
||||
src/org/mozilla/javascript/JavaScriptException.java,\
|
||||
src/org/mozilla/javascript/PropertyException.java,\
|
||||
src/org/mozilla/javascript/Script.java,\
|
||||
src/org/mozilla/javascript/Scriptable.java,\
|
||||
src/org/mozilla/javascript/ScriptableObject.java,\
|
||||
src/org/mozilla/javascript/SecurityController.java,\
|
||||
src/org/mozilla/javascript/WrapFactory.java,\
|
||||
src/org/mozilla/javascript/Wrapper.java,\
|
||||
src/org/mozilla/javascript/Synchronizer.java,\
|
||||
src/org/mozilla/javascript/serialize/ScriptableInputStream.java,\
|
||||
src/org/mozilla/javascript/serialize/ScriptableOutputStream.java
|
||||
@@ -1 +0,0 @@
|
||||
This version was built on @datestamp@.
|
||||
@@ -1,183 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!--
|
||||
Build file for Rhino using Ant (see http://jakarta.apache.org/ant/index.html)
|
||||
Requires Ant version 1.2 or later
|
||||
-->
|
||||
|
||||
<project name="Rhino" default="help" basedir=".">
|
||||
|
||||
<target name="properties">
|
||||
<property name="name" value="rhino"/>
|
||||
<property name="Name" value="Rhino"/>
|
||||
<property name="version" value="1_5R5pre"/>
|
||||
<property name="rhino.jar" value="js.jar"/>
|
||||
<property name="small-rhino.jar" value="smalljs.jar"/>
|
||||
|
||||
<property name="jar-compression" value="true"/>
|
||||
<property name="debug" value="on"/>
|
||||
|
||||
<property name="build.dir" value="./build"/>
|
||||
<property name="classes" value="${build.dir}/classes"/>
|
||||
|
||||
<property name="dist.name" value="rhino${version}"/>
|
||||
<property name="dist.dir" value="${build.dir}/${dist.name}"/>
|
||||
<property name="dist.src" value="${dist.dir}/src"/>
|
||||
<property name="dist.toolsrc" value="${dist.dir}/toolsrc"/>
|
||||
<property name="dist.examples" value="${dist.dir}/examples"/>
|
||||
<property name="dist.docs" value="${dist.dir}/docs"/>
|
||||
<property name="dist.apidocs" value="${dist.docs}/apidocs"/>
|
||||
<property name="dist.file" value="rhino${version}.zip"/>
|
||||
<property name="dist.source-only-zip" value="rhino${version}-sources.zip"/>
|
||||
|
||||
<property file="apiClasses.properties"/>
|
||||
<property name="docsrc.dir" value="docs"/>
|
||||
<property name="dist.docsrc.dir" value="src/docs"/>
|
||||
</target>
|
||||
|
||||
<target name="init" depends="properties">
|
||||
<mkdir dir="${build.dir}"/>
|
||||
<mkdir dir="${classes}"/>
|
||||
<mkdir dir="${dist.dir}"/>
|
||||
<mkdir dir="${dist.src}"/>
|
||||
<mkdir dir="${dist.toolsrc}"/>
|
||||
<mkdir dir="${dist.examples}"/>
|
||||
<mkdir dir="${dist.docs}"/>
|
||||
<mkdir dir="${dist.apidocs}"/>
|
||||
</target>
|
||||
|
||||
<target name="compile" depends="init">
|
||||
<ant dir="src" target="compile"/>
|
||||
<ant dir="toolsrc" target="compile"/>
|
||||
</target>
|
||||
|
||||
<target name="copy-source" depends="init">
|
||||
<ant dir="src" target="copy-source"/>
|
||||
<ant dir="toolsrc" target="copy-source"/>
|
||||
<copy todir="${dist.dir}" file="build.xml"/>
|
||||
<copy todir="${dist.dir}" file="apiClasses.properties"/>
|
||||
</target>
|
||||
|
||||
<target name="jar" depends="compile">
|
||||
<jar jarfile="${dist.dir}/${rhino.jar}"
|
||||
basedir="${classes}"
|
||||
manifest="src/manifest"
|
||||
compress="${jar-compression}"
|
||||
/>
|
||||
</target>
|
||||
|
||||
<target name="smalljar" depends="compile">
|
||||
|
||||
<jar basedir="${classes}" destfile="${dist.dir}/${small-rhino.jar}"
|
||||
compress="${jar-compression}">
|
||||
<include name="org/mozilla/javascript/*.class"/>
|
||||
<exclude name="org/mozilla/javascript/ClassNameHelper*.class"/>
|
||||
<exclude name="org/mozilla/javascript/ClassRepository*.class"/>
|
||||
<exclude name="org/mozilla/javascript/JavaAdapter*.class"/>
|
||||
<exclude name="org/mozilla/javascript/NotAFunctionException*.class"/>
|
||||
<exclude name="org/mozilla/javascript/Token.class"/>
|
||||
|
||||
<include name="org/mozilla/javascript/debug/*.class"/>
|
||||
<include name="org/mozilla/javascript/resources/*.properties"/>
|
||||
|
||||
<include name="org/mozilla/javascript/regexp/*.class"
|
||||
unless="no-regexp"/>
|
||||
</jar>
|
||||
|
||||
</target>
|
||||
|
||||
<target name="copy-examples" depends="init">
|
||||
<copy todir="${dist.examples}">
|
||||
<fileset dir="examples" includes="*.java,*.js,*.html" />
|
||||
</copy>
|
||||
</target>
|
||||
|
||||
<target name="copy-misc" depends="init">
|
||||
<tstamp/>
|
||||
<filter token="datestamp" value="${TODAY}"/>
|
||||
<copy todir="${dist.dir}" filtering="yes">
|
||||
<fileset dir=".">
|
||||
<patternset>
|
||||
<include name="build-date"/>
|
||||
</patternset>
|
||||
</fileset>
|
||||
</copy>
|
||||
</target>
|
||||
|
||||
<target name="copy-all" depends="copy-source,copy-examples,copy-misc">
|
||||
</target>
|
||||
|
||||
<target name="copy-docs" depends="init">
|
||||
<echo message="copy from ${docsrc.dir}"/>
|
||||
<copy todir="${dist.docs}">
|
||||
<fileset dir="${docsrc.dir}"
|
||||
includes="**/*.html,**/*.jpg,**/*.gif" />
|
||||
</copy>
|
||||
</target>
|
||||
|
||||
<target name="javadoc" depends="compile,copy-docs">
|
||||
<javadoc sourcefiles="${apiClasses}"
|
||||
sourcepath="src"
|
||||
destdir="${dist.apidocs}"
|
||||
overview="${dist.docs}/api.html"
|
||||
version="true"
|
||||
author="true"
|
||||
public="true"
|
||||
windowtitle="${Name}" />
|
||||
</target>
|
||||
|
||||
<target name="dist" depends="deepclean,jar,copy-all,javadoc">
|
||||
<delete file="${dist.file}" />
|
||||
<zip zipfile="${dist.file}"
|
||||
basedir="${build.dir}"
|
||||
includes="**"
|
||||
excludes="classes/**" />
|
||||
</target>
|
||||
|
||||
<target name="source-zip" depends="copy-source">
|
||||
<delete file="${dist.source-only-zip}" />
|
||||
<zip zipfile="${dist.source-only-zip}" basedir="${build.dir}"
|
||||
includes="${dist.name}/src/**,${dist.name}/toolsrc/**,${dist.name}/build.xml,${dist.name}/apiClasses.properties"/>
|
||||
</target>
|
||||
|
||||
<target name="clean" depends="properties">
|
||||
<delete quiet="true" file="${dist.dir}/${rhino.jar}"/>
|
||||
<delete quiet="true" file="${dist.dir}/${small-rhino.jar}"/>
|
||||
<delete quiet="true" dir="${classes}"/>
|
||||
</target>
|
||||
|
||||
<target name="deepclean" depends="properties">
|
||||
<delete quiet="true" dir="${build.dir}"/>
|
||||
<delete quiet="true" file="${dist.file}"/>
|
||||
<delete quiet="true" file="${dist.source-only-zip}"/>
|
||||
</target>
|
||||
|
||||
<target name="help" depends="properties">
|
||||
<echo>The following targets are available with this build file:
|
||||
|
||||
clean remove all compiled classes and copied property files
|
||||
|
||||
compile compile all classes and copy all property files
|
||||
into ${classes} directory
|
||||
|
||||
deepclean remove all generated files and directories
|
||||
|
||||
dist create ${dist.file} with full Rhino distribution
|
||||
|
||||
help print this help
|
||||
|
||||
jar create ${rhino.jar} in ${dist.dir}
|
||||
|
||||
smalljar create ${small-rhino.jar} in ${dist.dir} with
|
||||
minimalist set of Rhino classes. See footprint.html
|
||||
from the doc directory for details.
|
||||
|
||||
javadoc generate generate Rhino API documentation
|
||||
in ${dist.apidocs}
|
||||
|
||||
source-zip create ${dist.source-only-zip} with all Rhino
|
||||
source files necessary to recreate ${rhino.jar}
|
||||
</echo>
|
||||
</target>
|
||||
|
||||
</project>
|
||||
@@ -1,161 +0,0 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
|
||||
<META NAME="Generator" CONTENT="Microsoft Word 97">
|
||||
<TITLE>1</TITLE>
|
||||
</HEAD>
|
||||
<BODY>
|
||||
|
||||
<OL>
|
||||
|
||||
<B><FONT FACE="Arial" SIZE=5 COLOR="#000080"><LI>Using the Rhino JavaScript Debugger</LI>
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">The Mozilla Rhino JavaScript engine includes a source-level debugger for debugging JavaScript scripts. The debugger is itself a Java program which you may run as</P>
|
||||
</FONT><FONT FACE="Arial" SIZE=2><P ALIGN="JUSTIFY">java org.mozilla.javascript.tools.debugger.JSDebugger [options] [filename.js] [script-arguments]</P>
|
||||
</FONT><FONT SIZE=2><P ALIGN="JUSTIFY">where the options are the same as the shell.</P>
|
||||
<OL>
|
||||
|
||||
<LI><A NAME="_Toc502165108"></FONT><B><FONT FACE="Arial" SIZE=4 COLOR="#000080">Features</A></LI>
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">The Rhino JavaScript Debugger can debug scripts running in multiple threads and provides facilities to set and clear breakpoints, control execution, view variables, and evaluate arbitrary JavaScript code in the current scope of an executing script.</P>
|
||||
<OL>
|
||||
|
||||
<LI><A NAME="_Toc502165109"></FONT><B><FONT FACE="Arial" COLOR="#000080">Console Window</A></LI>
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">The debugger redirects the </FONT><FONT FACE="Arial" SIZE=2>System.out</FONT><FONT SIZE=2>, </FONT><FONT FACE="Arial" SIZE=2>System.in</FONT><FONT SIZE=2>, and </FONT><FONT FACE="Arial" SIZE=2>System.err</FONT><FONT SIZE=2> streams to an internal JavaScript console window which provides an editable command line for you to enter JavaScript code and view system output. The console window maintains a history of the commands you have entered. You may move backward and forward through the history list by pressing the Up/Down arrow keys on the keyboard.</P>
|
||||
<LI><A NAME="_Toc502165110"></FONT><B><FONT FACE="Arial" COLOR="#000080">Opening Scripts</A></LI>
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">You may select the <B><I>File->Open</B></I> menu item on the menu bar to load JavaScript scripts contained in files. This action will display a file-selection dialog box prompting you for the location of a script to load. The selected file will be compiled and displayed in a new window.</P>
|
||||
</FONT><B><FONT FACE="Arial" COLOR="#000080"><LI>Running Scripts</LI>
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">You may select the <B><I>File->Run</B></I> menu item on the menu bar to execute JavaScript scripts contained in files. This action will display a file-selection dialog box prompting you for the location of a script to execute. The loaded script will be run in a new thread and control will be given to the debugger on its first instruction.</P>
|
||||
<LI><A NAME="_Toc502165111"></FONT><B><FONT FACE="Arial" COLOR="#000080">Controlling Execution</A></LI>
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">The debugger provides the following facilities for you to control the execution of scripts you are debugging:</P>
|
||||
<OL>
|
||||
|
||||
</FONT><B><FONT FACE="Arial" COLOR="#000080"><LI>Step Into</LI></OL>
|
||||
</OL>
|
||||
</OL>
|
||||
</OL>
|
||||
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">To single step entering any function calls, you may do any of the following:</P>
|
||||
|
||||
<UL>
|
||||
<P ALIGN="JUSTIFY"><LI>Select the <B><I>Debug->Step Into </B></I>menu item on the menu bar</LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Press the <B><I>Step Into</B></I> button on the toolbar</LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Press the F11 key on the keyboard</LI></P></UL>
|
||||
|
||||
<P ALIGN="JUSTIFY">Execution will resume. If the current line in the script contains a function call control will return to the debugger upon entry into the function. Otherwise control will return to the debugger at the next line in the current function.</P>
|
||||
<OL>
|
||||
<OL>
|
||||
<OL>
|
||||
<OL>
|
||||
|
||||
</FONT><B><FONT FACE="Arial" COLOR="#000080"><LI>Step Over</LI></OL>
|
||||
</OL>
|
||||
</OL>
|
||||
</OL>
|
||||
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">To single step to the next line in the current function, you may do any of the following:</P>
|
||||
|
||||
<UL>
|
||||
<P ALIGN="JUSTIFY"><LI>Select the <B><I>Debug->Step Over</B></I> menu item on the menu bar</LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Press the <B><I>Step Over</B></I> button on the toolbar</LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Press the F7 key on the keyboard</LI></P></UL>
|
||||
|
||||
<P ALIGN="JUSTIFY">Execution will resume but control will return to the debugger at the next line in the current function or top-level script.</P>
|
||||
<OL>
|
||||
<OL>
|
||||
<OL>
|
||||
<OL>
|
||||
|
||||
</FONT><B><FONT FACE="Arial" COLOR="#000080"><LI>Step Out</LI></OL>
|
||||
</OL>
|
||||
</OL>
|
||||
</OL>
|
||||
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">To continue execution until the current function returns you may do any of the following:</P>
|
||||
|
||||
<UL>
|
||||
<P ALIGN="JUSTIFY"><LI>Select the <B><I>Debug->Step Out</B></I> menu item on the menu bar</LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Press the <B><I>Step Out</B></I> button on the toolbar</LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Press the F8 key on the keyboard</LI></P></UL>
|
||||
|
||||
<P ALIGN="JUSTIFY">Execution will resume until the current function returns or a breakpoint is hit.</P>
|
||||
<OL>
|
||||
<OL>
|
||||
<OL>
|
||||
<OL>
|
||||
|
||||
</FONT><B><FONT FACE="Arial" COLOR="#000080"><LI>Go</LI></OL>
|
||||
</OL>
|
||||
</OL>
|
||||
</OL>
|
||||
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">To resume execution of a script you may do any of the following:</P>
|
||||
|
||||
<UL>
|
||||
<P ALIGN="JUSTIFY"><LI>Select the <B><I>Debug->Go</B></I> menu item on the menu bar</LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Press the <B><I>Go</B></I> button on the toolbar</LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Press the F5 key on the keyboard</LI></P></UL>
|
||||
|
||||
<P ALIGN="JUSTIFY">Execution will resume until a breakpoint is hit or the script completes.</P>
|
||||
<P ALIGN="JUSTIFY"> </P>
|
||||
<OL>
|
||||
<OL>
|
||||
<OL>
|
||||
<OL>
|
||||
|
||||
</FONT><B><FONT FACE="Arial" COLOR="#000080"><LI>Break</LI></OL>
|
||||
</OL>
|
||||
</OL>
|
||||
</OL>
|
||||
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">To stop all running scripts and give control to the debugger you may do any of the following:</P>
|
||||
|
||||
<UL>
|
||||
<P ALIGN="JUSTIFY"><LI>Select the <B><I>Debug->Break</B></I> menu item on the menu bar</LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Press the <B><I>Break</B></I> button on the toolbar</LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Press the Pause/Break key on the keyboard</LI></P></UL>
|
||||
|
||||
<OL>
|
||||
<OL>
|
||||
<OL>
|
||||
|
||||
<LI><A NAME="_Toc502165112"></FONT><B><FONT FACE="Arial" COLOR="#000080">Moving Up and Down the Stack</A></LI>
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">The lower-left (dockable) pane in the debugger main window contains a combo-box labeled "Context:" which displays the current stack of the executing script. You may move up and down the stack by selecting an entry in the combo-box. When you select a stack frame the variables and watch windows are updated to reflect the names and values of the variables visible at that scope.</P>
|
||||
<LI><A NAME="_Toc502165113"></FONT><B><FONT FACE="Arial" COLOR="#000080">Setting and Clearing Breakpoints</A></LI></OL>
|
||||
</OL>
|
||||
</OL>
|
||||
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">The main desktop of the debugger contains file windows which display the contents of each script you are debugging. You may set a breakpoint in a script by doing one of the following:</P>
|
||||
|
||||
<UL>
|
||||
<P ALIGN="JUSTIFY"><LI>Place the cursor on the line at which you want to set a breakpoint and right-click with the mouse. This action will display a pop-up menu. Select the <B><I>Set Breakpoint</B></I> menu item. </LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Simply single-click on the line number of the line at which you want to set a breakpoint.</LI></P></UL>
|
||||
|
||||
<P ALIGN="JUSTIFY">If the selected line contains executable code a red dot will appear next to the line number and a breakpoint will be set at that location.</P>
|
||||
<P ALIGN="JUSTIFY">You may set clear breakpoint in a script by doing one of the following:</P>
|
||||
|
||||
<UL>
|
||||
<P ALIGN="JUSTIFY"><LI>Place the cursor on the line at which you want to clear a breakpoint and right-click with the mouse. This action will display a pop-up menu. Select the <B><I>Clear Breakpoint</B></I> menu item. </LI></P>
|
||||
<P ALIGN="JUSTIFY"><LI>Simply single-click on the red dot or the line number of the line at which you want to clear a breakpoint.</LI></P></UL>
|
||||
|
||||
<P ALIGN="JUSTIFY">The red dot will disappear and the breakpoint at that location will be cleared.</P>
|
||||
<OL>
|
||||
<OL>
|
||||
<OL>
|
||||
|
||||
<LI><A NAME="_Toc502165114"></FONT><B><FONT FACE="Arial" COLOR="#000080">Viewing Variables</A></LI>
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">The lower-left (dockable) pane in the debugger main window contains a tab-pane with two tabs, labeled "this" and "Locals". Each pane contains a tree-table which displays the properties of the current object and currently visible local variables, respectively. </P>
|
||||
<OL>
|
||||
|
||||
</FONT><B><FONT FACE="Arial" COLOR="#000080"><LI>This</LI></OL>
|
||||
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">The properties of the current object are displayed in the <B><I>this</B></I> table. If a property is itself a JavaScript object the property may be expanded to show its sub-properties. The <B><I>this</B></I> table is updated each time control returns to the debugger or when you change the stack location in the <B><I>Context:</B></I> window.</P>
|
||||
<LI><A NAME="_Toc502165115"></FONT><B><FONT FACE="Arial" COLOR="#000080">Locals</A></LI>
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">The local variables of the current function are displayed in the <B><I>Locals</B></I> table. If a variable is itself a JavaScript object the variable may be expanded to show its sub-properties. The <B><I>Locals</B></I> table is updated each time control returns to the debugger or when you change the stack location in the <B><I>Context:</B></I> window</P>
|
||||
<LI><A NAME="_Toc502165116"></FONT><B><FONT FACE="Arial" COLOR="#000080">Watch Window</A></LI>
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">You may enter arbitrary JavaScript expressions in the <B><I>Watch:</B></I> table located in the lower-right (dockable) pane in the debugger main window. The expressions you enter are reevaluated in the current scope and their current values displayed each time control returns to the debugger or when you change the stack location in the <B><I>Context:</B></I> window.</P>
|
||||
<LI><A NAME="_Toc502165117"></FONT><B><FONT FACE="Arial" COLOR="#000080">Evaluation Window</A></LI></OL>
|
||||
</OL>
|
||||
</OL>
|
||||
|
||||
</B></FONT><FONT SIZE=2><P ALIGN="JUSTIFY">The <B><I>Evaluate</B></I> pane located in the lower-right (dockable) pane in the debugger main window contains an editable command line where you may enter arbitrary JavaScript code. The code is evaluated in the context of the current stack frame. The window maintains a history of the commands you have entered. You may move backward or forward through the history by pressing the Up/Down arrow keys on the keyboard. </P>
|
||||
</FONT></BODY>
|
||||
</HTML>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,142 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.7 [en] (WinNT; U) [Netscape]">
|
||||
<title>JavaScript API</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
|
||||
<h1 align="center">
|
||||
Rhino API Reference.</h1>
|
||||
|
||||
<h4>
|
||||
The Control API</h4>
|
||||
These APIs provide methods for controlling the actions of JavaScript in
|
||||
a host environment.
|
||||
<ul>
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/Context.html">Context</a> - Represents
|
||||
the runtime context of an executing script. Has methods to associate the
|
||||
JavaScript evaluation engine with a Java thread, set attributes of the
|
||||
engine, and compile and evaluate scripts.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/ContextListener.html">ContextListener</a>
|
||||
- Allows embeddings to be notified of the creation, entering, exiting,
|
||||
and releasing of Contexts. </li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/Script.html">Script</a> - The result of
|
||||
compiling a JavaScript script. Also encapsulates script execution.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/ErrorReporter.html">ErrorReporter</a> -
|
||||
This interface can be implemented to control the actions the JavaScript
|
||||
engine takes when it encounters errors.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/SecurityController.html">SecurityController</a>
|
||||
- Optional support routines that must be provided by embeddings implementing
|
||||
security controls on scripts.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/ClassShutter.html">ClassShutter</a>
|
||||
- Embeddings that wish to filter Java classes that are visible to scripts
|
||||
through the LiveConnect, should implement this interface.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/Wrapper.html">Wrapper</a> - Interface implemented
|
||||
by objects wrapping other objects. Provides a method for recovering the
|
||||
wrapped value.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/WrapHandler.html">WrapHandler</a> - Interface
|
||||
embedders can implement in order to control the way Java objects are wrapped
|
||||
for use by JavaScript.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/ClassOutput.html">ClassOutput</a> - Interface
|
||||
embedders can implement in order to control the placement of generated
|
||||
class bytecodes.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/serialize/ScriptableOutputStream.html">ScriptableOutputStream</a> - This stream can be used to serialize JavaScript objects and functions.
|
||||
</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/serialize/ScriptableInputStream.html">ScriptableInputStream</a> - This stream can be used to deserialize JavaScript objects and functions.
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
|
||||
<h4>
|
||||
The Host Object API</h4>
|
||||
These APIs provide support for adding objects specific to a particular
|
||||
embedding of JavaScript in a host environment. Note that if you just want
|
||||
to script existing Java classes, you should just use <a href="http://developer.netscape.com/library/documentation/communicator/jsguide4/livecon.htm">LiveConnect</a>.
|
||||
It is also helpful to understand some of the implementation of the <a href="runtime.html">runtime</a>.
|
||||
<ul>
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/Scriptable.html">Scriptable</a> - All JavaScript
|
||||
objects must implement this interface. Provides methods to access properties
|
||||
and attributes of those properties, as well as other services required
|
||||
of JavaScript objects.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/Function.html">Function</a> - All JavaScript
|
||||
functions must implement this interface. Extends Scriptable, adding methods
|
||||
to support invocation.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/ScriptableObject.html">ScriptableObject</a>
|
||||
- A default implementation of Scriptable that may be extended. Implements
|
||||
property and attribute storage and lookup and other default JavaScript
|
||||
object behavior.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/FunctionObject.html">FunctionObject</a>
|
||||
- An implementation of Function that allows Java methods and constructors
|
||||
to be used as JavaScript function objects.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/ImporterTopLevel.html">ImporterTopLevel</a>
|
||||
- Allows embeddings to use the importClass and importPackage functions.</li>
|
||||
</ul>
|
||||
|
||||
<h4>
|
||||
Exceptions</h4>
|
||||
These exceptions are thrown by JavaScript.
|
||||
<ul>
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/JavaScriptException.html">JavaScriptException</a>
|
||||
- Thrown from within JavaScript by the JavaScript 'throw' statement, or
|
||||
by LiveConnect calls from JavaScript into Java. Wraps a JavaScript value.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/ClassDefinitionException.html">ClassDefinitionException</a>
|
||||
- Thrown if errors are detected while attempting to define a host object
|
||||
from a Java class.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/PropertyException.html">PropertyException</a>
|
||||
- Thrown if errors are detected while attempting to define a property of
|
||||
a host object from a Java class or method, or if a property is not found.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/NotAFunctionException.html">NotAFunctionException</a>
|
||||
- Thrown when attempting to call an object that is not a function.</li>
|
||||
|
||||
<li>
|
||||
<a href="org/mozilla/javascript/EvaluatorException.html">EvaluatorException</a>
|
||||
- An exception thrown when an error is detected during the execution of
|
||||
a script. The default error reporter will throw EvaluatorExceptions when
|
||||
an error is encountered.</li>
|
||||
</ul>
|
||||
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="overview-summary.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,43 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (WinNT; U) [Netscape]">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java, BSF, Apache">
|
||||
<title>Rhino and BSF</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
<script src="owner.js"></script>
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Using Rhino with BSF and Apache</h1></center>
|
||||
<script>document.write(owner());</script>
|
||||
|
||||
<br><script>
|
||||
var d = new Date(document.lastModified);
|
||||
document.write((d.getMonth()+1)+"/"+d.getDate()+"/"+d.getFullYear());
|
||||
document.write('<br>');
|
||||
</script>
|
||||
|
||||
<hr WIDTH="100%">
|
||||
<br>The <a href="http://oss.software.ibm.com/developerworks/projects/bsf">Bean
|
||||
Scripting Framework</a> (or BSF) was originally developed by IBM and now
|
||||
published as open source. It provides a framework for using a number of
|
||||
scripting languages with Java. Rhino is one of the supported languages.
|
||||
<p>This framework has been embedded in a number of open source projects,
|
||||
including the XSL processor <a href="http://xml.apache.org/xalan-j/index.html">Xalan</a>
|
||||
and the XML/Java build tool <a href="http://ant.apache.org/">Ant</a>.
|
||||
<p>You can download a version of <tt>bsf.jar</tt> from <a href="http://oss.software.ibm.com/developerworks/projects/bsf">http://oss.software.ibm.com/developerworks/projects/bsf</a>
|
||||
that includes the <tt>com.ibm.bsf.engines.javascript.JavaScriptEngine</tt>
|
||||
class. The current version is 2.2 release candidate at the time of this
|
||||
writing. This version thus supports JavaScript through Rhino when used
|
||||
with the <tt>js.jar</tt> file from either <tt>rhino15R1.zip</tt> or <tt>rhinoTip.zip</tt>.
|
||||
<p>See <a href="http://xml.apache.org/xalan/extensions.html#ex-basic">Xalan-Java
|
||||
Extensions</a> for more information on adding JavaScript to XSL and the
|
||||
<a href="http://jakarta.apache.org/ant/jakarta-ant/docs/#script">Script
|
||||
task</a> for using scripting in Ant build files.
|
||||
<p><a href="index.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,21 +0,0 @@
|
||||
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html><head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Change Log</title>
|
||||
</head>
|
||||
|
||||
<body bgcolor="#ffffff">
|
||||
|
||||
<h1 align="center">
|
||||
Change Log for Significant Rhino Changes</h1>
|
||||
|
||||
This is a log of significant changes since Rhino 1.5 Release 4.
|
||||
|
||||
<h3>Nothing significant yet!</h3>
|
||||
|
||||
<hr width="100%"><br>
|
||||
<a href="index.html">back to top</a></h3>
|
||||
|
||||
</body></html>
|
||||
@@ -1,249 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.7 [en] (WinNT; I) [Netscape]">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java, Debugger">
|
||||
<title>Rhino Debugger</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
<script src="owner.js">
|
||||
|
||||
</script>
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Rhino JavaScript Debugger</h1></center>
|
||||
Christopher Oliver
|
||||
<br><script>document.write(owner());</script>
|
||||
|
||||
<br>6/28/2001
|
||||
<center>
|
||||
<hr WIDTH="100%"></center>
|
||||
The Rhino JavaScript debugger is a GUI that allows debugging of interpreted
|
||||
JavaScript scripts run in Rhino. Note that this debugger <i>will not</i>
|
||||
work with JavaScript scripts run in the mozilla browser since Rhino is
|
||||
not the engine used in such environments.
|
||||
<p><img SRC="jsdebug.jpg" height=460 width=600>
|
||||
<p>Current limitations:
|
||||
<ul>
|
||||
<li>
|
||||
Requires JDK 1.2 or greater</li>
|
||||
|
||||
<li>
|
||||
Requires js.jar from rhinoTip.zip</li>
|
||||
|
||||
<li>
|
||||
No breakpoint menu</li>
|
||||
</ul>
|
||||
<b><font face="Arial"><font color="#000080"><font size=+2>Using the Rhino
|
||||
JavaScript Debugger</font></font></font></b>
|
||||
<p><font size=-1>The Mozilla Rhino JavaScript engine includes a source-level
|
||||
debugger for debugging JavaScript scripts. The debugger is itself a Java
|
||||
program which you may run as</font>
|
||||
<ol><font face="Arial"><font size=-1>java org.mozilla.javascript.tools.debugger.Main
|
||||
[options] [filename.js] [script-arguments]</font></font></ol>
|
||||
<font size=-1>where the options are the same as the shell.</font>
|
||||
<p><font size=-1>The Rhino JavaScript Debugger can debug scripts running
|
||||
in multiple threads and provides facilities to set and clear breakpoints,
|
||||
control execution, view variables, and evaluate arbitrary JavaScript code
|
||||
in the current scope of an executing script.</font>
|
||||
<p><a NAME="_Toc502165109"></a><b><font face="Arial"><font color="#000080"><font size=-1>Console
|
||||
Window</font></font></font></b>
|
||||
<br><font size=-1>The debugger redirects the <font face="Arial">System.out</font>,
|
||||
<font face="Arial">System.in</font>,
|
||||
and <font face="Arial">System.err</font> streams to an internal JavaScript
|
||||
console window which provides an editable command line for you to enter
|
||||
JavaScript code and view system output. The console window maintains a
|
||||
history of the commands you have entered. You may move backward and forward
|
||||
through the history list by pressing the Up/Down arrow keys on the keyboard.</font>
|
||||
<br><a NAME="_Toc502165110"></a><b><font face="Arial"><font color="#000080"><font size=-1>Opening
|
||||
Scripts</font></font></font></b>
|
||||
<br><font size=-1>You may select the <b><i>File->Open</i></b> menu item
|
||||
on the menu bar to load JavaScript scripts contained in files. This action
|
||||
will display a file-selection dialog box prompting you for the location
|
||||
of a script to load. The selected file will be compiled and displayed in
|
||||
a new window.</font>
|
||||
<br><a NAME="_RunningScripts"></a><b><font face="Arial"><font color="#000080"><font size=-1>Running
|
||||
Scripts</font></font></font></b>
|
||||
<br><font size=-1>You may select the <b><i>File->Run</i></b> menu item
|
||||
on the menu bar to execute JavaScript scripts contained in files. This
|
||||
action will display a file-selection dialog box prompting you for the location
|
||||
of a script to execute. The loaded script will be run in a new thread and
|
||||
control will be given to the debugger on its first instruction.</font>
|
||||
<p><a NAME="_Toc502165111"></a><b><font face="Arial"><font color="#000080"><font size=+1>Controlling
|
||||
Execution</font></font></font></b>
|
||||
<br><font size=-1>The debugger provides the following facilities for you
|
||||
to control the execution of scripts you are debugging:</font>
|
||||
<p><b><font face="Arial"><font color="#000080">Step Into</font></font></b>
|
||||
<br><font size=-1>To single step entering any function calls, you may do
|
||||
any of the following:</font>
|
||||
<ul>
|
||||
<li>
|
||||
<font size=-1>Select the <b><i>Debug->Step Into </i></b>menu item on the
|
||||
menu bar</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Press the <b><i>Step Into</i></b> button on the toolbar</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Press the F11 key on the keyboard</font></li>
|
||||
</ul>
|
||||
<font size=-1>Execution will resume. If the current line in the script
|
||||
contains a function call control will return to the debugger upon entry
|
||||
into the function. Otherwise control will return to the debugger at the
|
||||
next line in the current function.</font>
|
||||
<p><b><font face="Arial"><font color="#000080">Step Over</font></font></b>
|
||||
<br><font size=-1>To single step to the next line in the current function,
|
||||
you may do any of the following:</font>
|
||||
<ul>
|
||||
<li>
|
||||
<font size=-1>Select the <b><i>Debug->Step Over</i></b> menu item on the
|
||||
menu bar</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Press the <b><i>Step Over</i></b> button on the toolbar</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Press the F7 key on the keyboard</font></li>
|
||||
</ul>
|
||||
<font size=-1>Execution will resume but control will return to the debugger
|
||||
at the next line in the current function or top-level script.</font>
|
||||
<p><b><font face="Arial"><font color="#000080">Step Out</font></font></b>
|
||||
<br><font size=-1>To continue execution until the current function returns
|
||||
you may do any of the following:</font>
|
||||
<ul>
|
||||
<li>
|
||||
<font size=-1>Select the <b><i>Debug->Step Out</i></b> menu item on the
|
||||
menu bar</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Press the <b><i>Step Out</i></b> button on the toolbar</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Press the F8 key on the keyboard</font></li>
|
||||
</ul>
|
||||
<font size=-1>Execution will resume until the current function returns
|
||||
or a breakpoint is hit.</font>
|
||||
<p><b><font face="Arial"><font color="#000080">Go</font></font></b>
|
||||
<br><font size=-1>To resume execution of a script you may do any of the
|
||||
following:</font>
|
||||
<ul>
|
||||
<li>
|
||||
<font size=-1>Select the <b><i>Debug->Go</i></b> menu item on the menu
|
||||
bar</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Press the <b><i>Go</i></b> button on the toolbar</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Press the F5 key on the keyboard</font></li>
|
||||
</ul>
|
||||
<font size=-1>Execution will resume until a breakpoint is hit or the script
|
||||
completes.</font>
|
||||
<p><b><font face="Arial"><font color="#000080">Break</font></font></b>
|
||||
<br><font size=-1>To stop all running scripts and give control to the debugger
|
||||
you may do any of the following:</font>
|
||||
<ul>
|
||||
<li>
|
||||
<font size=-1>Select the <b><i>Debug->Break</i></b> menu item on the menu
|
||||
bar</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Press the <b><i>Break</i></b> button on the toolbar</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Press the Pause/Break key on the keyboard</font></li>
|
||||
</ul>
|
||||
|
||||
<a NAME="_RunningScripts"></a><b><font face="Arial"><font color="#000080"><font size=-1>Break
|
||||
on Exceptions</font></font></font></b>
|
||||
<br><font size=-1>To give control to the debugger whenever a JavaScript
|
||||
is exception is thrown select the <b><i>Debug->Break on Exceptions</i></b>
|
||||
checkbox from the menu bar. Whenever a JavaScript exception is thrown
|
||||
by a script a message dialog will be displayed and control will be given
|
||||
to the debugger at the location the exception is raised.</font>
|
||||
|
||||
<p><a NAME="_BreakOnFunctionEnter"></a><b><font face="Arial"><font color="#000080"><font size=-1>Break on Function Enter</font></font></font></b>
|
||||
<br><font size=-1>Selecting <b><i>Debug->Break on Function Enter</i></b> will give control to the debugger whenever the execution is entered into a function or script.</font>
|
||||
|
||||
<p><a NAME="_BreakOnFunctionExit"></a><b><font face="Arial"><font color="#000080"><font size=-1>Break on Function Exit</font></font></font></b>
|
||||
<br><font size=-1>Selecting <b><i>Debug->Break on Function Return</i></b> will give control to the debugger whenever the execution is about to return from a function or script.</font>
|
||||
|
||||
<p><a NAME="_Toc502165112"></a><b><font face="Arial"><font color="#000080">Moving
|
||||
Up and Down the Stack</font></font></b>
|
||||
<br><font size=-1>The lower-left (dockable) pane in the debugger main window
|
||||
contains a combo-box labeled "Context:" which displays the current stack
|
||||
of the executing script. You may move up and down the stack by selecting
|
||||
an entry in the combo-box. When you select a stack frame the variables
|
||||
and watch windows are updated to reflect the names and values of the variables
|
||||
visible at that scope.</font>
|
||||
<p><a NAME="_Toc502165113"></a><b><font face="Arial"><font color="#000080">Setting
|
||||
and Clearing Breakpoints</font></font></b>
|
||||
<br><font size=-1>The main desktop of the debugger contains file windows
|
||||
which display the contents of each script you are debugging. You may set
|
||||
a breakpoint in a script by doing one of the following:</font>
|
||||
<ul>
|
||||
<li>
|
||||
<font size=-1>Place the cursor on the line at which you want to set a breakpoint
|
||||
and right-click with the mouse. This action will display a pop-up menu.
|
||||
Select the <b><i>Set Breakpoint</i></b> menu item.</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Simply single-click on the line number of the line at which
|
||||
you want to set a breakpoint.</font></li>
|
||||
</ul>
|
||||
<font size=-1>If the selected line contains executable code a red dot will
|
||||
appear next to the line number and a breakpoint will be set at that location.</font>
|
||||
<p><font size=-1>You may clear breakpoint in a script by doing one of the
|
||||
following:</font>
|
||||
<ul>
|
||||
<li>
|
||||
<font size=-1>Place the cursor on the line at which you want to clear a
|
||||
breakpoint and right-click with the mouse. This action will display a pop-up
|
||||
menu. Select the <b><i>Clear Breakpoint</i></b> menu item.</font></li>
|
||||
|
||||
<li>
|
||||
<font size=-1>Simply single-click on the red dot or the line number of
|
||||
the line at which you want to clear a breakpoint.</font></li>
|
||||
</ul>
|
||||
<font size=-1>The red dot will disappear and the breakpoint at that location
|
||||
will be cleared.</font>
|
||||
<p><a NAME="_Toc502165114"></a><b><font face="Arial"><font color="#000080"><font size=+1>Viewing
|
||||
Variables</font></font></font></b>
|
||||
<br><font size=-1>The lower-left (dockable) pane in the debugger main window
|
||||
contains a tab-pane with two tabs, labeled "this" and "Locals". Each pane
|
||||
contains a tree-table which displays the properties of the current object
|
||||
and currently visible local variables, respectively.</font>
|
||||
<p><b><font face="Arial"><font color="#000080">This</font></font></b>
|
||||
<br><font size=-1>The properties of the current object are displayed in
|
||||
the
|
||||
<b><i>this</i></b> table. If a property is itself a JavaScript object
|
||||
the property may be expanded to show its sub-properties. The <b><i>this</i></b>
|
||||
table is updated each time control returns to the debugger or when you
|
||||
change the stack location in the <b><i>Context:</i></b> window.</font>
|
||||
<p><b><font face="Arial"><font color="#000080">Locals</font></font></b>
|
||||
<br><font size=-1>The local variables of the current function are displayed
|
||||
in the <b><i>Locals</i></b> table. If a variable is itself a JavaScript
|
||||
object the variable may be expanded to show its sub-properties. The <b><i>Locals</i></b>
|
||||
table is updated each time control returns to the debugger or when you
|
||||
change the stack location in the <b><i>Context:</i></b> window</font>
|
||||
<p><a NAME="_Toc502165116"></a><b><font face="Arial"><font color="#000080">Watch
|
||||
Window</font></font></b>
|
||||
<br><font size=-1>You may enter arbitrary JavaScript expressions in the
|
||||
<b><i>Watch:</i></b>
|
||||
table located in the lower-right (dockable) pane in the debugger main window.
|
||||
The expressions you enter are re-evaluated in the current scope and their
|
||||
current values displayed each time control returns to the debugger or when
|
||||
you change the stack location in the <b><i>Context:</i></b> window.</font>
|
||||
<p><a NAME="_Toc502165117"></a><b><font face="Arial"><font color="#000080">Evaluation
|
||||
Window</font></font></b>
|
||||
<br><font size=-1>The <b><i>Evaluate</i></b> pane located in the lower-right
|
||||
(dockable) pane in the debugger main window contains an editable command
|
||||
line where you may enter arbitrary JavaScript code. The code is evaluated
|
||||
in the context of the current stack frame. The window maintains a history
|
||||
of the commands you have entered. You may move backward or forward through
|
||||
the history by pressing the Up/Down arrow keys on the keyboard.</font>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,171 +0,0 @@
|
||||
<!DOCTYPE html PUBLIC "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
|
||||
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Rhino Documentation</title>
|
||||
</head>
|
||||
<body bgcolor="#ffffff">
|
||||
|
||||
<center>
|
||||
<h1> Rhino Documentation</h1>
|
||||
</center>
|
||||
<b><i><font size="+1">General</font></i></b>
|
||||
<table width="100%">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><a href="overview.html">Overview</a>
|
||||
</td>
|
||||
<td>An overview of the JavaScript language and of Rhino.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="limits.html">Requirements and Limitations</a>
|
||||
</td>
|
||||
<td>What you must have to run Rhino; what Rhino cannot do.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="rhino15R4.html">What's new in 1.5R4</a>
|
||||
</td>
|
||||
<td>Changes since 1.5R3.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="debugger.html">Rhino Debugger</a>
|
||||
</td>
|
||||
<td>A debugger for debugging JavaScript running in Rhino.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="opt.html">Optimization</a>
|
||||
</td>
|
||||
<td>Details on the various optimization levels.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="http://sourceforge.net/projects/jscorba">JS/CORBA Adapter</a>
|
||||
</td>
|
||||
<td>Provides a mechanism for arbitrary JavaScript objects to interact
|
||||
with each other transparently in a distributed JavaScript system using CORBA.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="bsf.html">Using Rhino with BSF and Apache</a>
|
||||
</td>
|
||||
<td>How to use Rhino with apps that support BSF.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="changes.html">Recent Changes</a>
|
||||
</td>
|
||||
<td>Describes recent changes to Rhino.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="faq.html">FAQ</a>
|
||||
</td>
|
||||
<td>Answers to frequently asked questions about Rhino.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="http://industry.java.sun.com/javaone/99/event/0,1768,629,00.html">
|
||||
1999 JavaOne session on Rhino</a>
|
||||
</td>
|
||||
<td>A talk on Rhino with slides. Also see the <a href="javaone.html">followup</a>
|
||||
.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="Top"><a href="http://www.ociweb.com/jnb/archive/jnbMar2001.html">
|
||||
Scripting Languages for Java</a>
|
||||
<br>
|
||||
</td>
|
||||
<td valign="Top">An article comparing and contrasting Rhino and Jython.<br>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p><b><i><font size="+1">Writing Scripts</font></i></b>
|
||||
<table width="100%">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><a href="ScriptingJava.html">Scripting Java</a>
|
||||
</td>
|
||||
<td>How to use Rhino to script Java classes.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="scriptjava.html">Scripting Java</a>
|
||||
</td>
|
||||
<td>How to use Rhino to script Java classes (an older treatment).</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="perf.html">Performance Hints</a>
|
||||
</td>
|
||||
<td>Some tips on writing faster JavaScript code.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="tools.html">Tools</a>
|
||||
</td>
|
||||
<td>Some tools for developing JavaScript scripts.</td>
|
||||
</tr>
|
||||
|
||||
</tbody>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
<p><b><i><font size="+1">Embedding Rhino</font></i></b>
|
||||
<table width="100%">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><a href="tutorial.html">Embedding tutorial</a>
|
||||
</td>
|
||||
<td>A short tutorial on how to embed Rhino into your application.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="apidocs/index.html">API javadoc Reference</a>
|
||||
</td>
|
||||
<td>An annotated outline of the programming interface to Rhino (tip only).</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="scopes.html">Scopes and Contexts</a>
|
||||
</td>
|
||||
<td>Describes how to use scopes and contexts for the best performance
|
||||
and flexibility, with an eye toward multithreaded environments.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="serialization.html">Serialization</a>
|
||||
</td>
|
||||
<td>How to serialize JavaScript objects and functions in Rhino.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="runtime.html">Runtime</a>
|
||||
</td>
|
||||
<td>A brief description of the JavaScript runtime.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="footprint.html">Small Footprint</a>
|
||||
</td>
|
||||
<td>Hints for those interested in small-footprint embeddings.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="examples.html">Examples</a>
|
||||
</td>
|
||||
<td>A set of examples showing how to control the JavaScript engine and
|
||||
build JavaScript host objects.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><font color="#000000"><a href="http://www.mozilla.org/js/tests/library.html">
|
||||
Testing</a>
|
||||
</font></td>
|
||||
<td>How to run the JavaScript test suite.</td>
|
||||
</tr>
|
||||
|
||||
</tbody>
|
||||
</table>
|
||||
</p>
|
||||
|
||||
<h3>
|
||||
<hr width="100%"><a href="index.html">back to top</a>
|
||||
</h3>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,91 +0,0 @@
|
||||
<!DOCTYPE html PUBLIC "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<meta name="Author" content="Igor Bukanov">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Rhino Downloads</title>
|
||||
</head>
|
||||
<body>
|
||||
<center><b><font size="+3">Rhino Downloads</font></b></center>
|
||||
<p>Rhino is available for download both in source and compiled form. </p>
|
||||
<h3> Binaries</h3>
|
||||
You can download binaries (JAR files) from <a
|
||||
href="ftp://ftp.mozilla.org/pub/mozilla.org/js/"> ftp://ftp.mozilla.org/pub/mozilla.org/js/</a>
|
||||
. Rhino 1.5 Release 4.1 is the last qualified release. It is also possible
|
||||
to download the latest rhino build that reflects newer features and bug
|
||||
fixes, but has not been fully qualified. These zip files also include
|
||||
the source.
|
||||
<p>If you are looking for <tt>js.jar</tt> for XSLT or for IBM's Bean
|
||||
Scripting Framework (BSF), download one of the zip files below and
|
||||
unzip it. </p>
|
||||
<ul>
|
||||
|
||||
<li> <a href="ftp://ftp.mozilla.org/pub/mozilla.org/js/rhino15R41.zip">Rhino 1.5R4.1.</a>
|
||||
<ul>
|
||||
<li> <i><font size="-1"><a href="rhino15R41.html">Description of changes from 1.5R4.1</a> </font></i>.</li>
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
<li> <a href="ftp://ftp.mozilla.org/pub/mozilla.org/js/rhino15R4.zip">Rhino 1.5R4.</a>
|
||||
<ul>
|
||||
<li> <i><font size="-1"><a href="rhino15R4.html">Description of changes from 1.5R3</a> </font></i>.</li>
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
<li><a href="ftp://ftp.mozilla.org/pub/mozilla.org/js/rhino15R3.zip">Rhino 1.5R3.</a>
|
||||
<ul>
|
||||
<li> <i><font size="-1"><a href="rhino15R3.html">Description of
|
||||
changes from 1.5R2</a> </font></i>.</li>
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
<li> <a
|
||||
href="ftp://ftp.mozilla.org/pub/mozilla.org/js/older-packages/rhino15R2.zip">Rhino
|
||||
1.5R2.</a>
|
||||
<ul>
|
||||
<li> <i><font size="-1"><a href="rhino15R2.html">Description of
|
||||
changes from 1.5R1</a> </font></i>.</li>
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
<li><a
|
||||
href="ftp://ftp.mozilla.org/pub/mozilla.org/js/older-packages/rhino15R1.zip">Rhino
|
||||
1.5R1.</a>
|
||||
<ul>
|
||||
<li> <i><font size="-1"><a href="rhino15R1.html">Description of
|
||||
changes from 1.4R3</a> </font></i>.</li>
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
<li> <a
|
||||
href="ftp://ftp.mozilla.org/pub/mozilla.org/js/older-packages/rhino14R3.zip"> Rhino
|
||||
1.4 Release 3</a> .</li>
|
||||
|
||||
<li> <a href="ftp://ftp.mozilla.org/pub/mozilla.org/js/rhinoLatest.zip">Latest
|
||||
Rhino builds</a> .
|
||||
<ul>
|
||||
<li> <i><font size="-1"><a href="changes.html">Description of
|
||||
changes from 1.5R4</a> </font></i>.</li>
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
</ul>
|
||||
<h3> Source</h3>
|
||||
The source code for Rhino is available under <a
|
||||
href="http://www.mozilla.org/NPL/"> NPL 1.1</a> . In addition to getting
|
||||
the source from the zip files above, the source code for Rhino can be
|
||||
found in the CVS tree at mozilla/js/rhino. See <a
|
||||
href="http://www.mozilla.org/cvs.html">source code via cvs</a> for
|
||||
details on how to set up CVS, define your CVSROOT, and login. Once
|
||||
you've done that, just execute the command
|
||||
<pre> cvs co mozilla/js/rhino</pre>
|
||||
to get the tip source.
|
||||
<p>The current tip can also be viewed using LXR at <a
|
||||
href="http://lxr.mozilla.org/mozilla/source/js/rhino/">
|
||||
http://lxr.mozilla.org/mozilla/source/js/rhino/</a> . </p>
|
||||
<p> </p>
|
||||
<hr width="100%"><a href="index.html">back to top</a> <br>
|
||||
<br>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,278 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Generator" content="Microsoft Word 97">
|
||||
<meta name="GENERATOR" content="Mozilla/4.7 [en] (WinNT; U) [Netscape]">
|
||||
<title>Embedding ‘Scripting Host’ in Business Applications</title>
|
||||
</head>
|
||||
<body link="#0000FF">
|
||||
<b><font face="Arial"><font size=-1>Embedding
|
||||
‘Scripting Host’ in Business Applications</font></font></b>
|
||||
<p><b><font face="Arial"><font size=-1>Madhukumar Seshadri, <a href="http://www.cognizant.com)/">www.cognizant.com</a></font></font></b>
|
||||
<br>
|
||||
<br>
|
||||
<p><font face="Arial"><font size=-1>With web browsers, continuing to rule
|
||||
the human interface for applications, creating value by being ubiquitous,
|
||||
few adoptions of rich technology that’s getting brewed underneath, will
|
||||
help designing business applications even though most of the current ones
|
||||
are made with bird’s eye of the underlying technologies.</font></font>
|
||||
<p><font face="Arial"><font size=-1>JavaScript is a scripting language
|
||||
invented and developed by Netscape. The language was primarily designed
|
||||
for creating lightweight programming for web browser extensions by exposing
|
||||
the Document Object Model of an HTML page to the scripts. JavaScript is
|
||||
becoming object oriented and getting adopted for server-side scripting.</font></font>
|
||||
<p><font face="Arial"><font size=-1>JavaScript is also becoming a standard
|
||||
in the scripting world as Netscape is working closely with ECMA (European
|
||||
Computer Manufacturers Association) to make it as a standard scripting
|
||||
language for the script world. The standards are published as ECMA Script.</font></font>
|
||||
<p><font face="Arial"><font size=-1>JavaScript originally designed for
|
||||
exposing the DOM (Document Object Model) standardized by World Wide Web
|
||||
consortium (W3C), to help web page designers to control and manipulate
|
||||
the pages dynamically. ‘JavaScript’ engines were embedded in the browsers
|
||||
and they execute those portions of the code embedded in the HTML pages.</font></font>
|
||||
<p><font face="Arial"><font size=-1>In short, JavaScript engine embedded
|
||||
in the browser allowed extensions or manipulations for DOM Object run time
|
||||
for the HTML page by executing the ‘scripts’ associated with them. In other
|
||||
words, browser exposes its DOM object for the page to scripts for extensions
|
||||
and dynamic manipulations of the same, using a language that the script
|
||||
interpreter understands.</font></font>
|
||||
<p><font face="Arial"><font size=-1>Can I do the same for my application
|
||||
by exposing my custom business objects written in my middle-tier? Can I
|
||||
allow user to my write JavaScript extensions for my objects and also be
|
||||
host for executing those scripts?</font></font>
|
||||
<p><font face="Arial"><font size=-1>JavaScript host runs times are available
|
||||
as binaries written in major languages. Check out <a href="http://www.mozilla.org/js">www.mozilla.org/js</a>.
|
||||
Spider Monkey and Rhino are open source JavaScripting engines available
|
||||
from mozilla.</font></font>
|
||||
<p><font face="Arial"><font size=-1>Microsoft implementation of ECMA Script
|
||||
(ECMA Script is based on core JavaScript, created by Netscape) is called
|
||||
JScript. Microsoft binaries of jscript engine can be downloaded from http://msdn.microsoft.com/scripting/.</font></font>
|
||||
<p><font face="Arial"><font size=-1>This document doesn’t explain the JavaScript
|
||||
language in detail but explains how these scripting engines can be used
|
||||
as host to expose business objects in the middle-tier and how the user
|
||||
of these applications can extend it if needed using JavaScript.</font></font>
|
||||
<p><font face="Arial"><font size=-1>The scripting engine Rhino (<a href="http://www.mozilla.org/js)">www.mozilla.org/rhino)</a>,
|
||||
a javascript engine purely written in Java is one that I am going to use
|
||||
for the testing the above.</font></font>
|
||||
<p><font face="Arial"><font size=-1>Let us set some simple goals,</font></font>
|
||||
<ul>
|
||||
<li>
|
||||
<font face="Arial"><font size=-1>Execute a plain ‘JavaScript’ code and
|
||||
use static Java object</font></font></li>
|
||||
|
||||
<li>
|
||||
<font face="Arial"><font size=-1>Instantiate external objects (written
|
||||
in Java) from the script and use them within the script</font></font></li>
|
||||
</ul>
|
||||
|
||||
<br>
|
||||
<br>
|
||||
<p><font face="Arial"><font size=-1>Let us write a simple Javscript to
|
||||
test the above set goals,</font></font>
|
||||
<p><font face="Arial"><font size=-1><b>Fig 1</b> – jshosttest.js</font></font>
|
||||
<p><b><i><font face="Arial"><font size=-1>/* Test 1 */</font></font></i></b>
|
||||
<br><b><i><font face="Arial"><font size=-1>/* Use a static Java Object
|
||||
in the script */</font></font></i></b>
|
||||
<p><font face="Arial"><font size=-1>function test1() {</font></font>
|
||||
<br><font face="Arial"><font size=-1> var str;</font></font>
|
||||
<br><font face="Arial"><font size=-1> str = '"Hello World";</font></font>
|
||||
<br><font face="Arial"><font size=-1> return str;</font></font>
|
||||
<br><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>var str = test1( );</font></font>
|
||||
<br><font face="Arial"><font size=-1>//out is expected to be Java Object
|
||||
exposed to the script scope</font></font>
|
||||
<br><font face="Arial"><font size=-1>out.println ("JavaScript - Test 1
|
||||
- " + str);</font></font>
|
||||
<p><b><i><font face="Arial"><font size=-1>/* Test 2 */</font></font></i></b>
|
||||
<p><b><i><font face="Arial"><font size=-1>/* Instantiate a Javaobject for
|
||||
this scope and use it */</font></font></i></b>
|
||||
<p><font face="Arial"><font size=-1>function test2(){</font></font>
|
||||
<br><font face="Arial"><font size=-1> // create a Java
|
||||
string buffer object from JavaScript and use its java instance</font></font>
|
||||
<br><font face="Arial"><font size=-1> // This uses an
|
||||
another Java object created for creating new objects within Java and</font></font>
|
||||
<br><font face="Arial"><font size=-1> // brings the same
|
||||
for JavaScript execution scope</font></font>
|
||||
<br><font face="Arial"><font size=-1> // Refer _create.java
|
||||
for more information</font></font>
|
||||
<br><font face="Arial"><font size=-1> create.getInstance("java.lang.StringBuffer","buffer");</font></font>
|
||||
<br><font face="Arial"><font size=-1> //JavaScript refers
|
||||
the java object instance as ‘buffer’</font></font>
|
||||
<br><font face="Arial"><font size=-1> out.println(buffer.toString());</font></font>
|
||||
<br> <font face="Arial"><font size=-1>buffer.append("I
|
||||
am a javaobject dynamically created and executed in JavaScript");</font></font>
|
||||
<br> <font face="Arial"><font size=-1>return buffer.toString();</font></font>
|
||||
<br><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>var str = test2();</font></font>
|
||||
<br><font face="Arial"><font size=-1>out.println("From JavaScript - Test
|
||||
2 " + str);</font></font>
|
||||
<p><font face="Arial"><font size=-1>Let us write a simple Javahost Object
|
||||
using the Rhino engine to execute the above script,</font></font>
|
||||
<p><b><font face="Arial"><font size=-1>Fig 2.1 - JSHost.java</font></font></b>
|
||||
<p><font face="Arial"><font size=-1>/**</font></font>
|
||||
<br><font face="Arial"><font size=-1>* @author Madhukumar Seshadri</font></font>
|
||||
<br><font face="Arial"><font size=-1>* @version</font></font>
|
||||
<br><font face="Arial"><font size=-1>*/</font></font>
|
||||
<p><font face="Arial"><font size=-1>import org.mozilla.javascript.*;</font></font>
|
||||
<br><font face="Arial"><font size=-1>import java.io.*;</font></font>
|
||||
<br><font face="Arial"><font size=-1>import java.lang.*;</font></font>
|
||||
<br><i><font face="Arial"><font size=-1>// import com.xxx.xxx.*;</font></font></i>
|
||||
<p><font face="Arial"><font size=-1>public class JSHost extends Object
|
||||
{</font></font>
|
||||
<br><font face="Arial"><font size=-1> /** Creates new
|
||||
JSHost */</font></font>
|
||||
<br><font face="Arial"><font size=-1> public JSHost()
|
||||
{</font></font>
|
||||
<br><font face="Arial"><font size=-1> }</font></font>
|
||||
<p><i><font face="Arial"><font size=-1> /*** Executes
|
||||
.js file ***/</font></font></i>
|
||||
<br><font face="Arial"><font size=-1> public Object executeJS
|
||||
(String jsfname){</font></font>
|
||||
<br><font face="Arial"><font size=-1> //You can also
|
||||
use evaluateReader</font></font>
|
||||
<br><font face="Arial"><font size=-1> File fp = new File(jsfname);</font></font>
|
||||
<br><font face="Arial"><font size=-1> String str_buff
|
||||
=null;</font></font>
|
||||
<br><font face="Arial"><font size=-1> try {</font></font>
|
||||
<br><font face="Arial"><font size=-1>
|
||||
FileReader fr = new FileReader(jsfname);</font></font>
|
||||
<br><font face="Arial"><font size=-1>
|
||||
int length = (int) fp.length();</font></font>
|
||||
<br><font face="Arial"><font size=-1>
|
||||
char cbuff[] = new char[(char)length];</font></font>
|
||||
<br><font face="Arial"><font size=-1>
|
||||
fr.read(cbuff);</font></font>
|
||||
<br><font face="Arial"><font size=-1>
|
||||
str_buff = new String(cbuff);</font></font>
|
||||
<br><font face="Arial"><font size=-1> } catch(Exception
|
||||
e) {</font></font>
|
||||
<br><font face="Arial"><font size=-1>
|
||||
e.printStackTrace();</font></font>
|
||||
<br><font face="Arial"><font size=-1> }</font></font>
|
||||
<p><font face="Arial"><font size=-1> //Execute the .js
|
||||
file content</font></font>
|
||||
<br><font face="Arial"><font size=-1> return executeJSSource(str_buff);</font></font>
|
||||
<br><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><i><font face="Arial"><font size=-1>/*** Executes javascript source
|
||||
***/</font></font></i>
|
||||
<br><font face="Arial"><font size=-1>public Object executeJSSource (String
|
||||
jsbuff){</font></font>
|
||||
<br><font face="Arial"><font size=-1>Object any=null;</font></font>
|
||||
<br><font face="Arial"><font size=-1>try{</font></font>
|
||||
<br><i><font face="Arial"><font size=-1>//Enter the Context</font></font></i>
|
||||
<br><font face="Arial"><font size=-1><i>// Refer </i><u><font color="#0000FF">http://www.mozilla.org/js/rhino/tutorial.html</font></u></font></font>
|
||||
<br><font face="Arial"><font size=-1>Context context = Context.enter();</font></font>
|
||||
<br><i><font face="Arial"><font size=-1>// Get the execution scope</font></font></i>
|
||||
<br><font face="Arial"><font size=-1>Scriptable scope = context.initStandardObjects();</font></font>
|
||||
<p><i><font face="Arial"><font size=-1>//----------- For Test 1 - Get System.out
|
||||
in scope</font></font></i>
|
||||
<br><font face="Arial"><font size=-1>//Scriptable jObj1 = Context.toObject(System.out,
|
||||
scope);</font></font>
|
||||
<br><font face="Arial"><font size=-1>scope.put("out", scope, jObj1);</font></font>
|
||||
<p><i><font face="Arial"><font size=-1>//------------ For Test 2 - Instantiate
|
||||
Create Object and get that in scope</font></font></i>
|
||||
<br><i><font face="Arial"><font size=-1>//Allow JScript to create Java
|
||||
Objects</font></font></i>
|
||||
<br><i><font face="Arial"><font size=-1>//Bring the _create object to context</font></font></i>
|
||||
<br><font face="Arial"><font size=-1>_create create = new _create( );</font></font>
|
||||
<br><i><font face="Arial"><font size=-1>//Register this context and scope
|
||||
to this create object instance</font></font></i>
|
||||
<br><font face="Arial"><font size=-1>create.registerContext(context,scope);</font></font>
|
||||
<br><font face="Arial"><font size=-1>//Scriptable jObj2 = Context.toObject(_create,
|
||||
scope);</font></font>
|
||||
<br><font face="Arial"><font size=-1>scope.put("create",scope,create);</font></font>
|
||||
<br><i><font face="Arial"><font size=-1>//Evaluate (or execute js)</font></font></i>
|
||||
<br><font face="Arial"><font size=-1><i>//Refer </i><u><font color="#0000FF">http://www.mozilla.org/js/rhino/tutorial.html</font></u></font></font>
|
||||
<br><font face="Arial"><font size=-1>any = context.evaluateString(scope,
|
||||
jsbuff, "", 1, null);</font></font>
|
||||
<br><i><font face="Arial"><font size=-1>//Exit the Context</font></font></i>
|
||||
<br><font face="Arial"><font size=-1>context.exit( );</font></font>
|
||||
<br><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>catch ( JavaScriptException jse) {</font></font>
|
||||
<br><font face="Arial"><font size=-1>jse.printStackTrace();</font></font>
|
||||
<br><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>return any;</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<br>
|
||||
<br>
|
||||
<p><font face="Arial"><font size=-1>Let us write a class for creating new
|
||||
Java objects and bringing them to this script execution scope,</font></font>
|
||||
<p><b><font face="Arial"><font size=-1>Fig 2.2 – _create.java</font></font></b>
|
||||
<p><i><font face="Arial"><font size=-1>/**</font></font></i>
|
||||
<p><i><font face="Arial"><font size=-1>* @author Madhukumar</font></font></i>
|
||||
<p><i><font face="Arial"><font size=-1>*/</font></font></i>
|
||||
<p><font face="Arial"><font size=-1>import java.lang.Class;</font></font>
|
||||
<p><font face="Arial"><font size=-1>import org.mozilla.javascript.*;</font></font>
|
||||
<p><font face="Arial"><font size=-1>public class _create extends Object
|
||||
{</font></font>
|
||||
<p><font face="Arial"><font size=-1>static Context ptr = null;</font></font>
|
||||
<p><font face="Arial"><font size=-1>static Scriptable scope =null;</font></font>
|
||||
<p><font face="Arial"><font size=-1>public _create () { }</font></font>
|
||||
<p><font face="Arial"><font size=-1>public void registerContext(Context
|
||||
cptr, Scriptable sc){</font></font>
|
||||
<p><font face="Arial"><font size=-1>ptr = cptr;</font></font>
|
||||
<p><font face="Arial"><font size=-1>scope = sc;</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>public void getInstance(String classname,String
|
||||
jsclassname) {</font></font>
|
||||
<p><font face="Arial"><font size=-1>Object any=null;</font></font>
|
||||
<p><font face="Arial"><font size=-1>try {</font></font>
|
||||
<p><font face="Arial"><font size=-1>Class thisclass = Class.forName(classname);</font></font>
|
||||
<p><font face="Arial"><font size=-1>any = thisclass.newInstance();</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>catch(Exception e){</font></font>
|
||||
<p><font face="Arial"><font size=-1>e.printStackTrace();</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>if( ptr != null) {</font></font>
|
||||
<p><font face="Arial"><font size=-1>if (scope !=null) {</font></font>
|
||||
<p><i><font face="Arial"><font size=-1>//register created object for this
|
||||
execution scope</font></font></i>
|
||||
<p><font face="Arial"><font size=-1>scope.put(jsclassname,scope,any);</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<br>
|
||||
<br>
|
||||
<p><font face="Arial"><font size=-1>It is time to test the code, so let
|
||||
us write a small object that will use the JSHost object,</font></font>
|
||||
<p><b><font face="Arial"><font size=-1>Fig 3 - JSHosttest.java</font></font></b>
|
||||
<p><font face="Arial"><font size=-1>/**</font></font>
|
||||
<p><font face="Arial"><font size=-1>* @author Madhukumar</font></font>
|
||||
<p><font face="Arial"><font size=-1>* @version</font></font>
|
||||
<p><font face="Arial"><font size=-1>*/</font></font>
|
||||
<p><font face="Arial"><font size=-1>public class JSHosttest extends Object
|
||||
{</font></font>
|
||||
<p><font face="Arial"><font size=-1>/** Creates new JSHostTest*/</font></font>
|
||||
<p><font face="Arial"><font size=-1>public JSHosttest() {</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>public static void main (String args[]){</font></font>
|
||||
<p><font face="Arial"><font size=-1>if (args.length < 1) {</font></font>
|
||||
<p><font face="Arial"><font size=-1>System.out.println("Usage - Java JSHosttest.class
|
||||
<js source file>");</font></font>
|
||||
<p><font face="Arial"><font size=-1>return;</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>JSHost jsh = new JSHost();</font></font>
|
||||
<p><font face="Arial"><font size=-1>System.out.println("Executing JavaScript
|
||||
file - " + args[0]);</font></font>
|
||||
<p><font face="Arial"><font size=-1>Object result = jsh.executeJS(args[0]);</font></font>
|
||||
<p><font face="Arial"><font size=-1>if (result instanceof String){</font></font>
|
||||
<p><font face="Arial"><font size=-1>System.out.println("Results - " + result);</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<p><font face="Arial"><font size=-1>}</font></font>
|
||||
<br>
|
||||
<br>
|
||||
<p><font face="Arial"><font size=-1>For more explanations on the code execution,
|
||||
please refer embedding tutorial <a href="http://www.mozilla.org/js/rhino/tutorial.html">http://www.mozilla.org/js/rhino/tutorial.html</a>
|
||||
and for all documentation and examples on Rhino visit <a href="http://www.mozilla.org/rhino/doc.html">http://www.mozilla.org/rhino/doc.html</a>.</font></font>
|
||||
<br>
|
||||
<br>
|
||||
<br>
|
||||
<br>
|
||||
<br>
|
||||
<br>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,94 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (WinNT; U) [Netscape]">
|
||||
<title>Rhino Examples</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Rhino Examples</h1></center>
|
||||
Examples have been provided that show how to control the JavaScript engine
|
||||
and to implement scriptable host objects. All the examples are in the cvs
|
||||
tree at <tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/">mozilla/js/rhino/examples</a></tt>.
|
||||
<br>
|
||||
<h2>
|
||||
Sample Scripts</h2>
|
||||
The <tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/unique.js">unique.js</a></tt>
|
||||
script allows printing unique lines from a file.
|
||||
<p>The <tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/liveConnect.js">liveConnect.js</a></tt>
|
||||
script shows a sample usage of LiveConnect (Java-to-JavaScript connectivity).
|
||||
<p>The <tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/jsdoc.js">jsdoc.js</a></tt>
|
||||
script is a JavaScript analog to Java's <tt>javadoc</tt>. It makes heavy
|
||||
use of regular expressions.
|
||||
<p>The <tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/checkParam.js">checkParam.js</a></tt>
|
||||
script is a useful tool to check that <tt>@param</tt> tags in Java documentation
|
||||
comments match the parameters in the corresponding Java method.
|
||||
<p>The <tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/enum.js">enum.js</a></tt>
|
||||
script is a good example of using a JavaAdapter to implement a Java interface
|
||||
using a JavaScript object.
|
||||
<p>The <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/NervousText.js">NervousText.js</a>
|
||||
script is a JavaScript implementation of the famous NervousText applet
|
||||
using JavaScript compiled to Java classes using <a href="jsc.html">jsc</a>.
|
||||
It can be run in the HTML page <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/NervousText.html">NervousText.html</a>.
|
||||
<br>
|
||||
<h2>
|
||||
Controlling the JavaScript Engine</h2>
|
||||
|
||||
<h4>
|
||||
The RunScript class</h4>
|
||||
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/RunScript.java">RunScript.java</a></tt>
|
||||
is a simple program that executes a script from the command line.
|
||||
<h4>
|
||||
The Control class</h4>
|
||||
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/Control.java">Control.java</a></tt>
|
||||
is a program that executes a simple script and then manipulates the result.
|
||||
<h4>
|
||||
JavaScript Shell</h4>
|
||||
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/Shell.java">Shell.java</a></tt>
|
||||
is a program that executes JavaScript programs; it is a simplified version
|
||||
of the shell in the <tt>tools</tt> package. The programs may be specified
|
||||
as files on the command line or by typing interactively while the shell
|
||||
is running.
|
||||
<h4>PrimitiveWrapFactory</h4>
|
||||
<a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/PrimitiveWrap
|
||||
Factory.java">PrimitiveWrapFactory.java</a> is an example of a WrapFactory that
|
||||
can be used to control the wrapping behavior of the Rhino engine on calls to Jav
|
||||
a methods.<br>
|
||||
<h4>
|
||||
<b>Multithreaded Script Execution</b></h4>
|
||||
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/DynamicScopes.java">DynamicScopes.java</a></tt>
|
||||
is a program that creates a single global scope object and then shares
|
||||
it across multiple threads. Sharing the global scope allows both information
|
||||
to be shared across threads, and amortizes the cost of Context.initStandardObjects
|
||||
by only performing that expensive operation once.
|
||||
<br>
|
||||
<h2>
|
||||
Implementing Host Objects</h2>
|
||||
First check out the <a href="http://www.mozilla.org/rhino/tutorial.html">tutorial</a>
|
||||
if you haven't already.
|
||||
<h4>
|
||||
The Foo class - Extending ScriptableObject</h4>
|
||||
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/Foo.java">Foo.java</a></tt>
|
||||
is a simple JavaScript host object that includes a property with an associated
|
||||
action and a variable argument method.
|
||||
<br>
|
||||
<h4>
|
||||
The Matrix class - Implementing Scriptable</h4>
|
||||
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/Matrix.java">Matrix.java</a></tt>
|
||||
provides a simple multidimensional array by implementing the Scriptable
|
||||
interface.
|
||||
<br>
|
||||
<h4>
|
||||
The File class - An advanced example</h4>
|
||||
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/File.java">File.java</a></tt>
|
||||
extends ScriptableObject to provide a means of reading and writing files
|
||||
from JavaScript. A more involved example of host object definition.
|
||||
<p>
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="index.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,52 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Rhino FAQ</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
<script src="owner.js"></script>
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Frequently Asked Questions about Rhino</h1></center>
|
||||
<script>document.write(owner());</script>
|
||||
|
||||
<br><script>
|
||||
var d = new Date(document.lastModified);
|
||||
document.write((d.getMonth()+1)+"/"+d.getDate()+"/"+d.getFullYear());
|
||||
document.write('<br>');
|
||||
</script>
|
||||
|
||||
<center>
|
||||
<hr WIDTH="100%"></center>
|
||||
|
||||
<p><b><font size=+2>Q</font>.</b> <i>How do I create a Java array from
|
||||
JavaScript?</i>
|
||||
<p><b><font size=+2>A.</font></b> You must use Java reflection. For instance,
|
||||
to create an array of java.lang.String of length five, do
|
||||
<blockquote><tt>var stringArray = java.lang.reflect.Array.newInstance(java.lang.String,
|
||||
5);</tt></blockquote>
|
||||
Then if you wish to assign the string "hi" to the first element, simply
|
||||
execute <tt>stringArray[0] = "hi"</tt>.
|
||||
<p>Creating arrays of primitive types is slightly different: you must use
|
||||
the TYPE field. For example, creating an array of seven ints can be done
|
||||
with the code
|
||||
<blockquote><tt>var intArray = java.lang.reflect.Array.newInstance(java.lang.Integer.TYPE,
|
||||
7);</tt></blockquote>
|
||||
|
||||
<p><br><b><font size=+2>Q</font>.</b> <i>When I try to execute a script
|
||||
I get the exception </i><tt>Required security context missing</tt><i>.
|
||||
What's going on?</i>
|
||||
<p><b><font size=+2>A.</font></b> You've likely missed placing the <tt>Security.properties</tt>
|
||||
file in your class path at <tt>org.mozilla.javascript.resources</tt>.
|
||||
<h3>
|
||||
|
||||
<hr WIDTH="100%"><br>
|
||||
<a href="index.html">back to top</a></h3>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,60 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.51 [en] (WinNT; U) [Netscape]">
|
||||
<title>Small Footprint</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Small Footprint</h1></center>
|
||||
A few changes can be made to reduce the footprint of Rhino for embeddings
|
||||
where space is at a premium. On a recent build, the length of js.jar was 603,127 bytes corresponding to 1,171,708 bytes of all uncompressed Rhino classes with debug information included.
|
||||
With various changes js.jar size can be reduced to 204,689 bytes corresponding to 424,774 bytes of uncompressed classes.
|
||||
|
||||
<h3>Tools</h3>
|
||||
<p>
|
||||
Most embeddings won't need any of the classes in <tt>org.mozilla.javascript.tools</tt> or any of its sub-packages.
|
||||
<h3>
|
||||
Optimizer</h3>
|
||||
<p>
|
||||
It is possible to run Rhino with interpreter mode only, allowing you to remove
|
||||
classes for classfile generation that include all the classes from
|
||||
<tt>org.mozilla.javascript.optimizer</tt> package and <tt>ClassNameHelper</tt>, <tt>ClassRepository</tt> classes from <tt>org.mozilla.javascript</tt> package.
|
||||
|
||||
<h3>JavaAdapter</h3>
|
||||
<p>
|
||||
Implementing the JavaAdapter functionality requires the ability to generate
|
||||
classes on the fly. Removing <tt>org.mozilla.javascript.JavaAdapter</tt> will disable this functionality, but Rhino will otherwise run correctly.
|
||||
|
||||
<h3>Class generation library</h3>
|
||||
<p>
|
||||
If you do not include Optimizer or JavaAdapter, then you do not need Rhino library for class file generation and you can remove all the classes from in <tt>org.mozilla.classfile</tt> package.
|
||||
|
||||
<h3>Regular Expressions</h3>
|
||||
<p>
|
||||
The package <tt>org.mozilla.javascript.regexp</tt> can be removed. Rhino
|
||||
will continue to run, although it will not be able to execute any regular
|
||||
expression matches. This change saves 47,984 bytes of class files.
|
||||
|
||||
<h3>Debug information</h3>
|
||||
<p>
|
||||
Debug information in Rhino classes consumes about 25% of code size and if you can live without that, you can recompile Rhino to remove it.
|
||||
|
||||
<h2>smalljs.jar</h2>
|
||||
|
||||
Ant build script in Rhino supports smalljar target that will generate smalljs.jar that does not include Tools, Optimizer, JavaAdapter and Class generation library, Regular Expressions and deprecated files. To build such minimalist jar without debug information, run the following command from the top directory of Rhino distribution:
|
||||
<pre>
|
||||
ant clean
|
||||
ant -Ddebug=off -Dno-regexp=true smalljar
|
||||
</pre>
|
||||
If you omit <tt>-Dno-regexp=true</tt>, then the resulting smalljs.jar will include Regular Expression support.
|
||||
|
||||
<p>
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="index.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,44 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
|
||||
<title>Help with Rhino</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<center><b><font size=+3>Help with Rhino</font></b></center>
|
||||
<script src="owner.js"></script>
|
||||
|
||||
<p>Have a question that you can't find answer to in the <a href="doc.html">documentation</a>?
|
||||
Here are some additional resources for help:
|
||||
<br>
|
||||
<h3>
|
||||
<font size=+1>Newsgroup and Mail Gateway</font></h3>
|
||||
The <a href="news:netscape.public.mozilla.jseng">netscape.public.mozilla.jseng</a>
|
||||
newsgroup answers questions about both Rhino and the C implementation of
|
||||
JavaScript. You can get to the newsgroup through a mail gateway. Send a
|
||||
message with the subject "subscribe" to <a href="mailto:mozilla-jseng-request@mozilla.org?subject=subscribe">mozilla-jseng-request@mozilla.org</a>.
|
||||
To post messages, send mail to <a href="mailto:mozilla-jseng@mozilla.org">mozilla-jseng@mozilla.org</a>.
|
||||
To unsubscribe, mail with "unsubscribe" in the subject to <a href="mailto:mozilla-jseng-request@mozilla.org?subject=unsubscribe">mozilla-jseng-request@mozilla.org</a>.
|
||||
<p>
|
||||
To view archived messages, try <a href="http://groups.google.com/groups?q=netscape.public.mozilla.jseng&hl=en&lr=&safe=off&site=groups">Google groups</a> or
|
||||
other newsgroup services.
|
||||
<h3>
|
||||
Bug System</h3>
|
||||
Use <a href="http://bugzilla.mozilla.org/enter_bug.cgi?product=Rhino">Bugzilla</a>
|
||||
to enter bugs against Rhino. Note that Rhino has its own product category.
|
||||
<br>
|
||||
<h3>
|
||||
Module Owner</h3>
|
||||
The module owner, <script>document.write(owner());</script>
|
||||
, can
|
||||
be mailed for help as well, although he may copy his response to the newsgroup
|
||||
to help others.
|
||||
<p>
|
||||
<hr WIDTH="100%"><a href="index.html">back to top</a>
|
||||
<br>
|
||||
<br>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,45 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.72 [en]C-NSCP (WinNT; U) [Netscape]">
|
||||
<title>Rhino History</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<center><b><font size=+3>Rhino History</font></b></center>
|
||||
|
||||
<p>Rhino gets its name from the animal on the cover of the <a href="http://www.ora.com/">O'Reilly</a>
|
||||
book about JavaScript.
|
||||
<p>The Rhino project was started at Netscape in Fall 1997. At the time,
|
||||
Netscape was planning to produce a version of Navigator written entirely
|
||||
in Java and so it needed an implementation of JavaScript written in Java.
|
||||
When Netscape stopped work on "Javagator", as it was called, somehow Rhino
|
||||
escaped the axe (rumor had it that the executives "forgot" it existed).
|
||||
Since then, a couple of major companies (including Sun) have licensed Rhino
|
||||
for use in their products and paid Netscape to do so, allowing us to continue
|
||||
work on it. Now Rhino is planned to be part of several server products
|
||||
from Netscape as well.
|
||||
<p>Originally, Rhino compiled all JavaScript code to Java bytecodes in
|
||||
generated classfiles. This produced the best performance (often beating
|
||||
the C implementation of JavaScript when run on a JIT), but suffered from
|
||||
two faults. First, compilation time was long since generating Java bytecodes
|
||||
and loading the generated classes was a heavyweight process. Also, the
|
||||
implementation effectively leaked memory since most JVMs don't really collect
|
||||
unused classes or the strings that are interned as a result of loading
|
||||
a class file.
|
||||
<p>So in Fall of 1998, Rhino added an interpretive mode. The classfile
|
||||
generation code was moved to an optional, dynamically-loaded package. Compilation
|
||||
is faster and when scripts are no longer in use they can be collected like
|
||||
any other Java object.
|
||||
<p>Rhino was released to mozilla.org in April of 1998. Originally Rhino
|
||||
classfile generation had been held back from release. However the licensees
|
||||
of Rhino have now agreed to release all of Rhino to open source, including
|
||||
class file generation. Since its release to open source, Rhino has found
|
||||
a variety of <a href="users.html">uses</a> and an increasing
|
||||
number of people have contributed to the code.
|
||||
<p>
|
||||
<hr WIDTH="100%"><a href="index.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,75 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.7 [en] (WinNT; U) [Netscape]">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java, Mozilla">
|
||||
<title>Rhino - JavaScript for Java</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Rhino: JavaScript for Java</h1></center>
|
||||
|
||||
<center><img SRC="rhino50.jpg" height=200 width=398></center>
|
||||
|
||||
<hr WIDTH="100%">Rhino is an open-source implementation of JavaScript written
|
||||
entirely in Java. It is typically embedded into Java applications to provide
|
||||
scripting to end users.
|
||||
<table WIDTH="100%" >
|
||||
<tr>
|
||||
<td>
|
||||
<div align=right><b><a href="download.html">Downloads</a></b></div>
|
||||
</td>
|
||||
|
||||
<td>How to get source and binaries.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<div align=right><b><a href="doc.html">Documentation</a></b></div>
|
||||
</td>
|
||||
|
||||
<td>Information on Rhino for script writers and embedders.</td>
|
||||
</tr>
|
||||
|
||||
<!--
|
||||
<tr>
|
||||
<td>
|
||||
<div align=right><b><a href="users.html">Users</a></b></div>
|
||||
</td>
|
||||
|
||||
<td>How people are using Rhino.</td>
|
||||
</tr>
|
||||
-->
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<div align=right><b><a href="history.html">History</a></b></div>
|
||||
</td>
|
||||
|
||||
<td>The ancestry of the beast.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<div align=right><b><a href="help.html">Help</a></b></div>
|
||||
</td>
|
||||
|
||||
<td>Some resources if you get stuck.</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<hr WIDTH="100%"><font size=-1>Module owner </font><script src="owner.js"></script>
|
||||
<script>document.write(owner());</script>
|
||||
|
||||
<br><font size=-1>Rhino image courtesy of Paul Houle.</font><!---
|
||||
Add reference to
|
||||
http://www.javaworld.com/jw-08-1999/jw-08-howto.html
|
||||
and
|
||||
http://www.javaworld.com/javaworld/jw-09-1999/jw-09-howto.html
|
||||
--->
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,66 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.6 [en] (WinNT; U) [Netscape]">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Followup to JavaOne</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Followup to JavaOne session on Rhino</h1></center>
|
||||
This page is intended to follow up on the <a href="http://www.javasoft.com/javaone/">JavaOne</a>
|
||||
session on <a href="http://industry.java.sun.com/javaone/99/event/0,1768,629,00.html">"Rhino:
|
||||
JavaScript for the Java Platform"</a>. I hope it will be useful whether
|
||||
or not you actually attended the talk.
|
||||
<br>
|
||||
<h2>
|
||||
Slides</h2>
|
||||
<a href="http://industry.java.sun.com/javaone/99/pdfs/e629.pdf">Slides</a>
|
||||
(PDF file, 1112246 bytes) can be downloaded from Sun's site.
|
||||
<br>
|
||||
<br>
|
||||
<h2>
|
||||
More on Q & A</h2>
|
||||
Following the talk there was an excellent question and answer session where
|
||||
many attendees asked good questions and offered useful suggestions. I'll
|
||||
follow up on some of those here. I'll start a thread on the newsgroup <a href="news://news.mozilla.org/netscape.public.mozilla.jseng">netscape.public.mozilla.jseng</a>
|
||||
so people can ask addition questions or comments there.
|
||||
<h3>
|
||||
Java classes visible to scripts</h3>
|
||||
One attendee raised the point that many embeddings may not want scripts
|
||||
to be able to access all Java classes. This is an excellent point, and
|
||||
I've implemented an addition to the <a href="../js/rhino/org/mozilla/javascript/SecuritySupport.html">SecuritySupport</a>
|
||||
class that allows embedders to choose which classes are exposed to scripts.
|
||||
<h3>
|
||||
Easier "importing" of Java classes</h3>
|
||||
Another attendee suggested that the current method of referring to Java
|
||||
classes (like <tt>java.lang.String</tt> or <tt>Packages.org.mozilla.javascript.Context</tt>)
|
||||
could be improved. I've implemented a set of changes that make importing
|
||||
easier, but I'm not convinced that adding them is the right thing to do
|
||||
due to some drawbacks.
|
||||
<p>To see what I've done, take a look at the javadoc for the <a href="../js/rhino/org/mozilla/javascript/ImporterTopLevel.html">ImporterTopLevel</a>
|
||||
class. You'll see that it's now possible to make function calls to "import"
|
||||
Java classes so that they can be referred to without qualification. I didn't
|
||||
use the word "import" because that's a keyword in JavaScript.
|
||||
<p>There are a few drawbacks to this implemenation. First, there is a runtime
|
||||
cost associated with every lookup of a top-level variable. The problem
|
||||
is that it's not possible to use the Java runtime to determine the set
|
||||
of classes from a given package. Instead, importing the package "java.util"
|
||||
saves the package name in a special list and every access to the global
|
||||
scope that fails to find a matching variable causes the runtime to see
|
||||
if there is a class by that name in the "java.util" package. Even for lookups
|
||||
that succeed there is an additional method call.
|
||||
<p>Another drawback to this implementation is namespace pollution: now
|
||||
"importClass" and "importPackage" have special meaning. It's still possible
|
||||
to substitute your own variables for these functions, but it's still possible
|
||||
that program behavior could change.
|
||||
<p>So I'm interested in people's opinion: Is this benefit worth the costs?
|
||||
<p>
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="index.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,82 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.7 [en] (WinNT; U) [Netscape]">
|
||||
<title>JavaScript Compiler</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
JavaScript Compiler</h1></center>
|
||||
The JavaScript compiler translates JavaScript source into Java class files.
|
||||
The resulting Java class files can then be loaded and executed at another
|
||||
time, providing a convenient method for transfering JavaScript, and for
|
||||
avoiding translation cost.
|
||||
<p>Note that the top-level functions available to the shell (such as <tt>print</tt>)
|
||||
are <i>not</i> available to compiled scripts when they are run outside
|
||||
the shell.
|
||||
<br>
|
||||
<h2>
|
||||
Invoking the Compiler</h2>
|
||||
<tt>java org.mozilla.javascript.tools.jsc.Main</tt> [<i>options</i>] <i>file1</i><tt>.js</tt>
|
||||
[<i>file2</i><tt>.js</tt>...]
|
||||
<p>where <i>options</i> are:
|
||||
<p><tt>-extends <i>java-class-name</i></tt>
|
||||
<blockquote>Specifies that a java class extending the Java class <i>java-class-name</i>
|
||||
should be generated from the incoming JavaScript source file. Each global
|
||||
function in the source file is made a method of the generated class, overriding
|
||||
any methods in the base class by the same name.</blockquote>
|
||||
<tt>-implements <i>java-intf-name</i></tt>
|
||||
<blockquote>Specifies that a java class implementing the Java interface
|
||||
<i><tt>java-intf-name</tt></i>
|
||||
should be generated from the incoming JavaScript source file. Each global
|
||||
function in the source file is made a method of the generated class, implementing
|
||||
any methods in the interface by the same name.</blockquote>
|
||||
<tt>-debug</tt>
|
||||
<br><tt>-g</tt>
|
||||
<ul>Specifies that debug information should be generated. May not be combined
|
||||
with optimization at an <i>optLevel</i> greater than zero.</ul>
|
||||
<tt>-nosource</tt>
|
||||
<ul>Does not save the source in the class file. Functions and scripts compiled
|
||||
this way cannot be decompiled. This option can be used to avoid distributing
|
||||
source or simply to save space in the resulting class file.</ul>
|
||||
<tt>-o </tt><i>outputFile</i>
|
||||
<ul>Writes the class file to the given file (which should end in <tt>.class</tt>).
|
||||
The string <i>outputFile</i> must be a writable filename.</ul>
|
||||
<tt>-opt </tt><i>optLevel</i>
|
||||
<br><tt>-O</tt> <i>optLevel</i>
|
||||
<ul>Optimizes at level <i>optLevel</i>, which must be an integer between
|
||||
-1 and 9. See <a href="opt.html">Optimization</a> for more details. If
|
||||
<i>optLevel</i>
|
||||
is greater than zero, <tt>-debug</tt> may not be specified.</ul>
|
||||
<tt>-package</tt> <i>packageName</i>
|
||||
<ul>Specifies the package to generate the class into. The string <i>packageName</i>
|
||||
must be composed of valid identifier characters optionally separated by
|
||||
periods.</ul>
|
||||
<tt>-version </tt><i>versionNumber</i>
|
||||
<ul>Specifies the language version to compile with. The string <i>versionNumber</i>
|
||||
must be one of <tt>100</tt>, <tt>110</tt>, <tt>120</tt>, <tt>130</tt>,
|
||||
or <tt>140</tt>. See <a href="overview.html#versions">JavaScript Language
|
||||
Versions</a> for more information on language versions.</ul>
|
||||
|
||||
<h2>
|
||||
Examples</h2>
|
||||
<tt>$ cat test.js</tt>
|
||||
<br><tt>java.lang.System.out.println("hi, mom!");</tt>
|
||||
<br><tt>$ java org.mozilla.javascript.tools.jsc.Main test.js</tt>
|
||||
<br><tt>$ ls *.class</tt>
|
||||
<br><tt>test.class</tt>
|
||||
<br><tt>$ java test</tt>
|
||||
<br><tt>hi, mom!</tt>
|
||||
<p><tt>$ java org.mozilla.javascript.tools.jsc.Main -extends java.applet.Applet
|
||||
\</tt>
|
||||
<br><tt> -implements java.lang.Runnable NervousText.js</tt>
|
||||
<br>
|
||||
<p>
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="index.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 60 KiB |
@@ -1,86 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.72 [en]C-NSCP (WinNT; U) [Netscape]">
|
||||
<title>JavaScript Requirements and Limitations</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Requirements and Limitations</h1></center>
|
||||
|
||||
<h2>
|
||||
<b>Requirements</b></h2>
|
||||
Rhino requires version 1.1 or greater of Java.
|
||||
<p>To use the JavaAdapter feature or an optimization level of 0 or greater,
|
||||
Rhino must be running under a security manager that allows the definition
|
||||
of class loaders.
|
||||
<p>
|
||||
<hr WIDTH="100%">
|
||||
<h2>
|
||||
<b>Limitations</b></h2>
|
||||
|
||||
<h3>
|
||||
<b>Platforms and </b>JITs</h3>
|
||||
Many platforms and JREs have problems converting decimal numbers to and
|
||||
from strings. These errors are usually boundary case errors and will show
|
||||
up as test failures in section 7.7.3.
|
||||
<p>Windows versions of the Symantec JIT prior to 3.00.029(i) will report
|
||||
internal errors for some generated class files.
|
||||
<p>On the Symantec JIT and the AIX JVM, accessing a static field of a class
|
||||
that has not yet loaded may not give the correct value of the field. For
|
||||
example, accessing
|
||||
<tt>java.io.File.separatorChar</tt> before <tt>java.io.File</tt>
|
||||
has been loaded will return a value of 0. (This is a bug in the JIT; accessing
|
||||
the field should cause the class to be loaded.)
|
||||
<p>The AIX Java version "JDK 1.1.6 IBM build a116-19980924 (JIT enabled:
|
||||
jitc)" core dumps running several classes generated by Rhino. It also has
|
||||
errors in java.lang.Math.pow that are reflected as failures in the JavaScript
|
||||
Math object's pow method.
|
||||
<p>IBM Java for Linux version "JDK 1.1.8 IBM build l118-19991013 (JIT enabled:
|
||||
jitc)" has errors in java.lang.Math.pow that are reflected as test failures
|
||||
in the JavaScript Math object's pow method.
|
||||
<p>Solaris JDK 1.1.6 has errors in java.lang.Math.atan2 that are reflected
|
||||
as test failures in the JavaScript Math object's atan2 method.
|
||||
<br>
|
||||
<h3>
|
||||
<b>LiveConnect</b></h3>
|
||||
If a JavaObject's field's name collides with that of a method, the value
|
||||
of that field is retrieved lazily, and can be counter-intuitively affected
|
||||
by later assignments:
|
||||
<blockquote><tt>javaObj.fieldAndMethod = 5;</tt>
|
||||
<br><tt>var field = javaObj.fieldAndMethod;</tt>
|
||||
<br><tt>javaObj.fieldAndMethod = 7;</tt>
|
||||
<br><tt>// now, field == 7</tt></blockquote>
|
||||
You can work around this by forcing the field value to be converted to
|
||||
a JavaScript type when you take its value:
|
||||
<blockquote><tt>javaObj.fieldAndMethod = 5;</tt>
|
||||
<br><tt>var field = javaObj.fieldAndMethod + 0; // force conversion now</tt>
|
||||
<br><tt>javaObj.fieldAndMethod = 7;</tt>
|
||||
<br><tt>// now, field == 5</tt></blockquote>
|
||||
|
||||
<h3>
|
||||
<b>JSObject</b></h3>
|
||||
Rhino does NOT support the <tt>netscape.javascript.JSObject</tt> class.
|
||||
<br>
|
||||
<h3>
|
||||
<b>Date object</b></h3>
|
||||
The JavaScript Date object depends on time facilities of the underlying
|
||||
Java runtime to determine daylight savings time dates. Earlier JRE versions
|
||||
may report a date for the daylight savings changeover that is a week off.
|
||||
JRE 1.1.6 reports the correct date.
|
||||
<p>Under the 1.1.6 JRE, evaluating <tt>(new Date(1998, 9, 25, 2)).toString()</tt>
|
||||
returns:
|
||||
<pre> Sun Oct 25 02:00:00 GMT-0800 (PST) 1998</pre>
|
||||
Earlier versions may return:
|
||||
<pre> Sun Oct 25 02:00:00 GMT-0700 (PDT) 1998</pre>
|
||||
(the JRE doesn't report the changeover until Nov. 1.)
|
||||
<p>The Microsoft SDK 3.1 for Java also exhibits this problem.
|
||||
<p>
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="rhino.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 19 KiB |
@@ -1,68 +0,0 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
|
||||
<META NAME="Author" CONTENT="Norris Boyd">
|
||||
<META NAME="GENERATOR" CONTENT="Mozilla/4.05 [en] (WinNT; U) [Netscape]">
|
||||
<TITLE>Optimization</TITLE>
|
||||
</HEAD>
|
||||
<BODY BGCOLOR="#FFFFFF">
|
||||
|
||||
<CENTER>
|
||||
<H1>
|
||||
Optimization</H1></CENTER>
|
||||
|
||||
<H2>
|
||||
Optimization settings</H2>
|
||||
<P>The currently supported optimization settings are:</P>
|
||||
|
||||
<P><B>-1</B>
|
||||
|
||||
<P><B></B>Interpretive mode is always
|
||||
used. The compilation time is minimized at the expense of runtime performance.
|
||||
No class files are generated, which may improve memory usage depending on your
|
||||
system.
|
||||
<p>
|
||||
If the optimization package is not available, then optimization acts as if it is always -1.
|
||||
</P>
|
||||
|
||||
<P><B>0</B>
|
||||
|
||||
<P><B></B>No optimizations are
|
||||
performed. The bytecode compiler runs fastest in this mode, but the generated byte code
|
||||
is less efficient.</P>
|
||||
|
||||
<P><B>1-9</B>
|
||||
|
||||
<P>All optimizations are performed. Simple data & type
|
||||
flow analysis is performed to determine which JavaScript variables can be
|
||||
allocated to Java VM registers, and which variables are used only as Numbers.
|
||||
Local common sub-expressions are collapsed (currently this only happens for
|
||||
property lookup, but in the future more expressions may be optimized). All local
|
||||
variables and parameters are allocated to Java VM registers. Function call
|
||||
targets are speculatively pre-cached (based on the name used in the source) so
|
||||
that dispatching can be direct, pending runtime confirmation of the actual
|
||||
target. Arguments are passed as Object/Number pairs to reduce conversion
|
||||
overhead.</P>
|
||||
|
||||
<P>Note:
|
||||
<OL>
|
||||
<LI>
|
||||
Some language features (indirect calls to eval, use
|
||||
of the arguments property of function objects) were previously not supported
|
||||
in higher optimization levels. These features have been removed from the
|
||||
language in ECMA, so higher optimization levels are now conformant.
|
||||
|
||||
<LI>
|
||||
Future versions may allocate more aggressive
|
||||
optimizations to higher optimization levels. For compatibility with future
|
||||
versions, use level 1. For maximal optimization, use level 9, but retest
|
||||
your application when upgrading to new versions.</LI>
|
||||
</OL>
|
||||
|
||||
|
||||
<P>
|
||||
<HR WIDTH="100%">
|
||||
<BR><A HREF="index.html">back to top</A>
|
||||
<br>
|
||||
</BODY>
|
||||
</HTML>
|
||||
@@ -1,148 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.72 [en]C-NSCP (WinNT; U) [Netscape]">
|
||||
<title>JavaScript Overview</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Rhino Overview</h1></center>
|
||||
|
||||
<h3>
|
||||
Overview of Rhino</h3>
|
||||
Most people who have used JavaScript before have done so by adding scripts
|
||||
to their HTML web pages. However, Rhino is an implementation of the core
|
||||
language only and doesn't contain objects or methods for manipulating HTML
|
||||
documents.
|
||||
<p>Rhino contains
|
||||
<ul>
|
||||
<li>
|
||||
All the features of JavaScript 1.5</li>
|
||||
|
||||
<li>
|
||||
Allows direct scripting of Java</li>
|
||||
|
||||
<li>
|
||||
A JavaScript shell for executing JavaScript scripts</li>
|
||||
|
||||
<li>
|
||||
A JavaScript compiler to transform JavaScript source files into Java class
|
||||
files</li>
|
||||
</ul>
|
||||
|
||||
<h3>
|
||||
Language</h3>
|
||||
The JavaScript language itself is standardized by Standard ECMA-262 <i>ECMAScript:
|
||||
A general purpose, cross-platform programming language</i>. Rhino 1.5 implements
|
||||
JavaScript 1.5, which conforms to Edition 3 of the Standard. The Standard
|
||||
may be <a href="http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM">downloaded</a> or
|
||||
obtained by mail from ECMA, 114 Rue du Rhône, CH1204 Geneva, Switzerland.
|
||||
<p>In addition, Rhino has implemented JavaAdapters, which allows JavaScript
|
||||
to implement any Java interface or extend any Java class with a JavaScript
|
||||
object. See the <tt>enum.js</tt> example for more information.
|
||||
<p>Numerous books and tutorials on JavaScript are available.
|
||||
<br>
|
||||
<br>
|
||||
<h3>
|
||||
Deprecated Language Features</h3>
|
||||
Several language features introduced in JavaScript 1.2 are now deprecated.
|
||||
These features allow "computational reflection": that is, the ability for
|
||||
a script to determine and influence aspects of the way it is evaluated.
|
||||
These features are generally not broadly useful, yet they impose significant
|
||||
constraints on implementations that hamper or prevent optimization. The
|
||||
deprecated features are the <tt>__proto__</tt> and <tt>__parent__</tt>
|
||||
properties, and the constructors <tt>With</tt>, <tt>Closure</tt>, and <tt>Call</tt>.
|
||||
Attempts to invoke these constructors with the language version 1.4 will
|
||||
result in an error. For other versions, a warning will be generated.
|
||||
<br>
|
||||
<br>
|
||||
<h3>
|
||||
Internationalization</h3>
|
||||
The messages reported by the JavaScript engine are by default retrieved
|
||||
from the property file <tt>org/mozilla/javascript/resources/Messages.properties</tt>.
|
||||
If other properties files with extensions corresponding to the current
|
||||
locale exist, they will be used instead.
|
||||
<br>
|
||||
<br>
|
||||
<h3>
|
||||
<a NAME="versions"></a>JavaScript Language Versions</h3>
|
||||
Some behavior in the JavaScript engine is dependent on the language version.
|
||||
In browser embeddings, this language version is selected using the LANGUAGE
|
||||
attribute of the SCRIPT tag with values such as "JavaScript1.2".
|
||||
<p>Version 1.3 and greater are ECMA conformant.
|
||||
<p><b>Operators <tt>==</tt> and <tt>!=</tt></b>
|
||||
<p>Version 1.2 only uses strict equality for the == and != operators. In
|
||||
version 1.3 and greater, == and != have the same meanings as ECMA. The
|
||||
operators === and !== use strict equality in all versions.
|
||||
<p><b>ToBoolean</b>
|
||||
<p><tt>Boolean(new Boolean(false))</tt> is false for all versions before
|
||||
1.3. It is true (and thus ECMA conformant) for version 1.3 and greater.
|
||||
<p><b>Array.prototype.toString and Object.prototype.toString</b>
|
||||
<p>Version 1.2 only returns array or object literal notation ("[1,2,3]"
|
||||
or "{a:1, b:2}" for example). In version 1.3 and greater these functions
|
||||
are ECMA conformant.
|
||||
<p><b>Array constructor</b>
|
||||
<p><tt>Array(i)</tt> for a number argument <tt>i</tt> constructs an array
|
||||
with a single element equal to <tt>i</tt> for version 1.2 only. Otherwise
|
||||
the ECMA conformant version is used (an array is constructed with no elements
|
||||
but with length property equal to <tt>i</tt>).
|
||||
<p><b>String.prototype.substring</b>
|
||||
<p>For version 1.2 only, the two arguments are not swapped if the first
|
||||
argument is less than the second one. All other versions are ECMA compliant.
|
||||
<p><b>String.prototype.split</b>
|
||||
<p>For version 1.2 only, split performs the Perl4 special case when given
|
||||
a single space character as an argument (skips leading whitespace, and
|
||||
splits on whitespace). All other versions split on the space character
|
||||
proper as specified by ECMA.
|
||||
<br>
|
||||
<br>
|
||||
<h3>
|
||||
Security</h3>
|
||||
The security features in Rhino provide the ability to track the origin
|
||||
of a piece of code (and any pieces of code that it may in turn generate).
|
||||
These features allow for the implementation of a traditional URL-based
|
||||
security policy for JavaScript as in Netscape Navigator. Embeddings that
|
||||
trust the JavaScript code they execute may ignore the security features.
|
||||
<p>Embeddings that run untrusted JavaScript code must do two things to
|
||||
enable the security features. First, every <tt>Context</tt> that is created
|
||||
must be supplied an instance of an object that implements the <tt>SecuritySupport</tt>
|
||||
interface. This will provide Rhino the support functionality it needs to
|
||||
perform security-related tasks.
|
||||
<p>Second, the value of the property <tt>security.requireSecurityDomain</tt>
|
||||
should be changed to <tt>true</tt> in the resource bundle <tt>org.mozilla.javascript.resources.Security</tt>.
|
||||
The value of this property can be determined at runtime by calling the
|
||||
<tt>isSecurityDomainRequired</tt>
|
||||
method of <tt>Context</tt>. Setting this property to true requires that
|
||||
any calls that compile or evaluate JavaScript must supply a security domain
|
||||
object of any object type that will be used to identify JavaScript code.
|
||||
In a typical client embedding, this object might be a string with the URL
|
||||
of the server that supplied the script, or an object that contains a representation
|
||||
of the signers of a piece of code for certificate-based security policies.
|
||||
<p>When JavaScript code attempts a restricted action, the security domain
|
||||
can be retrieved in the following manner. The class context should be obtained
|
||||
from the security manager (see <tt>java.lang.SecurityManager.getClassContext()</tt>).
|
||||
Then, the class of the code that called to request the restricted action
|
||||
can be obtained by looking an appropriate index into the class context
|
||||
array. If the caller is JavaScript the class obtained may be one of two
|
||||
types. First, it may be the class of the interpreter if interpretive mode
|
||||
is in effect. Second, it may be a generated class if classfile generation
|
||||
is supported. An embedding can distinguish the two cases by calling <tt>isInterpreterClass()</tt>
|
||||
in the <tt>Context</tt> class. If it is the interpreter class, call the
|
||||
getInterpreterSecurityDomain() method of Context to obtain the security
|
||||
domain of the currently executing interpreted script or function. Otherwise,
|
||||
it must be a generated class, and an embedding can call <tt>getSecurityDomain()</tt>
|
||||
in the class implementing
|
||||
<tt>SecuritySupport</tt>. When the class was
|
||||
defined and loaded, the appropriate security domain was associated with
|
||||
it, and can be retrieved by calling this method. Once the security domain
|
||||
has been determined, an embedding can perform whatever checks are appropriate
|
||||
to determine whether access should be allowed.
|
||||
<p>
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="index.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,3 +0,0 @@
|
||||
function owner() {
|
||||
return '<a href="mailto:nboyd'+'@'+ 'atg.com">Norris Boyd</a>'
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.5 [en]C-NSCP (WinNT; I) [Netscape]">
|
||||
<title>Performance Hints</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Performance Hints</h1></center>
|
||||
<h3>
|
||||
<tt>var</tt> Statements</h3>Use <tt>var</tt> statements when possible. Not only is it good
|
||||
programming practice, it can speed up your code by allowing the compiler to
|
||||
generate special code to access the variables. For example, you could rewrite
|
||||
<p><tt>function sum(a) {</tt>
|
||||
<br><tt> result = 0;</tt>
|
||||
<br><tt> for (i=0; i <
|
||||
a.length; i++)</tt>
|
||||
<br><tt> result += a[i];</tt>
|
||||
<br><tt> return result;</tt>
|
||||
<br><tt>}</tt>
|
||||
<p>as
|
||||
<p><tt>function sum(a) {</tt>
|
||||
<br><tt> var result = 0;</tt>
|
||||
<br><tt> for (var i=0; i
|
||||
< a.length; i++)</tt>
|
||||
<br><tt> result += a[i];</tt>
|
||||
<br><tt> return result;</tt>
|
||||
<br><tt>}</tt>
|
||||
<p>This is not equivalent code because the second version does
|
||||
not modify global variables <tt>result</tt> and <tt>i</tt>. However, if you don't intend for any other function to
|
||||
access these variables, then storing them globally is probably wrong anyway
|
||||
(what if you called another function that had a loop like the one in <tt>sum</tt>!).
|
||||
<br>
|
||||
<h3>
|
||||
Arrays</h3>Use the forms of the Array constructor that
|
||||
specify a size or take a list of initial elements. For example, the code
|
||||
<p><tt>var a = new Array();</tt>
|
||||
<br><tt>for (var i=0; i < n; i++)</tt>
|
||||
<br><tt> a[i] = i;</tt>
|
||||
<p>could be sped up by changing the constructor call to <tt>new Array(n)</tt>. A constructor call like that indicates to
|
||||
the runtime that a Java array should be used for the first <i>n</i> entries of the array. Similarly,
|
||||
<tt>new
|
||||
Array("a", "b", "c")</tt> or <tt>["a", "b", "c"]</tt> will cause a 3-element
|
||||
Java array to be allocated to hold the contents of the JavaScript array.
|
||||
<br>
|
||||
<br>
|
||||
<h3>
|
||||
<tt>eval</tt> and <tt>new Function</tt></h3>Avoid calling <tt>eval</tt> when
|
||||
possible. Calls to <tt>eval</tt> are slow because the script
|
||||
being executed must be compiled. Constructing a new function object can be slow
|
||||
for the same reason, while function expressions are more efficient because the
|
||||
function can be compiled. For example, the code
|
||||
<p><tt>function MyObject(a) {</tt>
|
||||
<br><tt> this.s = a;</tt>
|
||||
<br><tt> this.toString = new
|
||||
Function("return this.s");</tt>
|
||||
<br><tt>}</tt>
|
||||
<p>could be written more efficiently as
|
||||
<p><tt>function MyObject(a) {</tt>
|
||||
<br><tt> this.s = a;</tt>
|
||||
<br><tt> this.toString =
|
||||
function () { return this.s }</tt>
|
||||
<br><tt>}</tt>
|
||||
<p>Beginning with Rhino 1.4 Release 2, code
|
||||
passed to eval and new Function will be interpreted rather than compiled to
|
||||
class files.
|
||||
<br> </p>
|
||||
<h3>
|
||||
with</h3>Using the <tt>with</tt>
|
||||
statement prevents the compiler from generating code for fast access to local
|
||||
variables. You're probably better off explicitly accessing any properties of the
|
||||
object.
|
||||
<br>
|
||||
<p>
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="index.html">back to top</a>
|
||||
<br>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,162 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>What's New in Rhino 1.5</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
What's New in Rhino 1.5 Release 1</h1></center>
|
||||
|
||||
<h2>
|
||||
ECMA 262 Edition 3 Conformance</h2>
|
||||
Rhino 1.5 implements JavaScript 1.5, which conforms to ECMA 262 Edition
|
||||
3 (sometimes referred to as "ECMAScript"). Edition 3 standardized several
|
||||
features of JavaScript that were present in JavaScript 1.4, including:
|
||||
<ul>
|
||||
<li>
|
||||
regular expressions</li>
|
||||
|
||||
<li>
|
||||
<tt>switch</tt> statements</li>
|
||||
|
||||
<li>
|
||||
<tt>do</tt>...<tt>while</tt> loops</li>
|
||||
|
||||
<li>
|
||||
statement labels and labelled <tt>break</tt> and <tt>continue</tt></li>
|
||||
|
||||
<li>
|
||||
object literals</li>
|
||||
|
||||
<li>
|
||||
nested functions</li>
|
||||
|
||||
<li>
|
||||
exception handling</li>
|
||||
|
||||
<li>
|
||||
the <tt>instanceof</tt> operator</li>
|
||||
|
||||
<li>
|
||||
the <tt>in</tt> operator</li>
|
||||
</ul>
|
||||
In addition, new features were added to Edition 3 and JavaScript 1.5, including:
|
||||
<ul>
|
||||
<li>
|
||||
Perl 5 regular expressions, including operators like greedy quantifiers</li>
|
||||
|
||||
<li>
|
||||
errors as exceptions</li>
|
||||
|
||||
<li>
|
||||
number formatting (<tt>Number.prototype.toFixed</tt>, <tt>Number.prototype.toExponential</tt>,
|
||||
and <tt>Number.prototype.toGeneral</tt>)</li>
|
||||
</ul>
|
||||
|
||||
<h2>
|
||||
Changes since Rhino 1.4 Release 3</h2>
|
||||
Other significant changes to Rhino since the initial release to open source
|
||||
(1.4 Release 3) are listed below. Bug fixes won't be mentioned here, just
|
||||
API changes or significant functionality changes.
|
||||
<h3>
|
||||
Compilation mode</h3>
|
||||
Rhino has two modes of execution available. Interpretive mode has an interpreter
|
||||
loop implemented in Java. Compilation mode compiles JavaScript code to
|
||||
Java bytecodes in class files. This compilation can be done as part of
|
||||
script evaluation using the same APIs already available for the interpreter,
|
||||
or in a separate compile-time step. The code for the interpreter is located
|
||||
in the <tt>org.mozilla.javascript.optimizer</tt> package.
|
||||
<br>
|
||||
<h3>
|
||||
JavaScript Compiler</h3>
|
||||
The distribution now contains an extra class that can be invoked from the
|
||||
command line. This is <tt>jsc</tt>, the JavaScript compiler. This tool
|
||||
can be used to create Java classes from JavaScript. Options exist to allow
|
||||
creation of Java classes that implement arbitrary interfaces and extend
|
||||
arbitrary base classes, allowing JavaScript scripts to implement important
|
||||
protocols like applets and servlets. See <a href="http://www.mozilla.org/rhino/jsc.html">http://www.mozilla.org/rhino/jsc.html</a>.
|
||||
<br>
|
||||
<h3>
|
||||
LiveConnect 3</h3>
|
||||
Rhino now supports the LiveConnect 3 specification, or LC3. The most notable
|
||||
change is support for overloaded method resolution. See <a href="http://www.mozilla.org/js/liveconnect/lc3_proposal.html">LiveConnect
|
||||
Release 3 Goals/Features</a>.
|
||||
<br>
|
||||
<h3>
|
||||
JavaBeans properties reflected as Java properties</h3>
|
||||
Java classes with getFoo/setFoo methods will have a "foo" property in the
|
||||
JavaScript reflection. Boolean methods are also reflected.
|
||||
<br>
|
||||
<h3>
|
||||
Dynamic scope support</h3>
|
||||
Rhino 1.5 implements support for dynamic scopes, which are particularly
|
||||
useful for multithreaded environments like server embeddings.
|
||||
<br>
|
||||
<h3>
|
||||
New semantics for <tt>ScriptableObject.defineClass</tt></h3>
|
||||
The old rules for defining JavaScript objects using a Java class were getting
|
||||
baroque. Those rules are still supported, but a cleaner definition is now
|
||||
supported. See the <a href="http://www.mozilla.org/js/rhino/org/mozilla/javascript/ScriptableObject.html#defineClass(org.mozilla.javascript.Scriptable, java.lang.Class)">javadoc</a>
|
||||
for details.
|
||||
<br>
|
||||
<h3>
|
||||
Support for the Java 2 <tt>-jar</tt> option</h3>
|
||||
It's now possible to start the shell using the new <tt>-jar</tt> option
|
||||
in Java 2.
|
||||
<br>
|
||||
<h3>
|
||||
Shell changes</h3>
|
||||
Two changes here: addition of the "environment" and "history" top-level
|
||||
variables.
|
||||
<br>
|
||||
<h3>
|
||||
Java classes visible to scripts</h3>
|
||||
An attendee at JavaOne raised the point that many embeddings may not want
|
||||
scripts to be able to access all Java classes. This is an excellent point,
|
||||
and I've implemented an addition to the <a href="../js/rhino/org/mozilla/javascript/SecuritySupport.html">SecuritySupport</a>
|
||||
interface that allows embedders to choose which classes are exposed to
|
||||
scripts.
|
||||
<br>
|
||||
<h3>
|
||||
SecuritySupport and JavaAdapter</h3>
|
||||
Andrew Wason pointed a problem with the new JavaAdapter feature (which
|
||||
allows JavaScript objects to implement arbitrary Java interfaces by generating
|
||||
class files). It didn't support the <a href="../js/rhino/org/mozilla/javascript/SecuritySupport.html">SecuritySupport</a>
|
||||
interface, which allows Rhino to delegate the creation of classes from
|
||||
byte arrays to a routine provided by the embedding. This ability is important
|
||||
from a security standpoint because class creation is considered a privileged
|
||||
action.
|
||||
<p>I've checked in changes that fix this problem. If a SecuritySupport
|
||||
class is specified when a Context is created, uses of JavaAdapter will
|
||||
will delegate class creation to the SecuritySupport class.
|
||||
<br>
|
||||
<h3>
|
||||
Context.exit()</h3>
|
||||
Context.exit() has been changed from an instance method to a static method.
|
||||
This makes it match the Context.enter() method, which is also static. See
|
||||
the <a href="http://www.mozilla.org/js/rhino/org/mozilla/javascript/Context.html#exit()">javadoc</a>
|
||||
for more information on its operation.
|
||||
<br>
|
||||
<h3>
|
||||
Context.enter(Context)</h3>
|
||||
A new overloaded form of Context.enter has been added. Without the addition
|
||||
of this method it was not possible to attach an existing context to a thread.
|
||||
See the <a href="http://www.mozilla.org/js/rhino/org/mozilla/javascript/Context.html#enter(org.mozilla.javascript.Context)">javadoc</a>
|
||||
for more information on its operation.
|
||||
<br>
|
||||
<h3>
|
||||
Listeners for Context</h3>
|
||||
Context now supports property change listeners for a couple of its properties.
|
||||
<h3>
|
||||
|
||||
<hr WIDTH="100%"><br>
|
||||
<a href="index.html">back to top</a></h3>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,84 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Rhino 1.5 Release 2</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
What's New in Rhino 1.5 Release 2</h1></center>
|
||||
This is a log of significant changes since the release of Rhino 1.5 Release
|
||||
1.
|
||||
<br>
|
||||
<h2>
|
||||
Graphical debugger</h2>
|
||||
Thanks to a contribution by Christopher Oliver, Rhino now has a graphical
|
||||
debugger. See <a href="debugger.html">Rhino Debugger</a> for more details.
|
||||
<br>
|
||||
<h2>
|
||||
Footprint reductions</h2>
|
||||
Igor Bukanov has provided a wealth of changes to reduce the number and
|
||||
size of objects required by Rhino. In particular, he introduced a new way
|
||||
to represent the built-in objects like Date and RegExp that reduces the
|
||||
amount of memory required and speeds up <tt>Context.initStandardObjects</tt>.
|
||||
<br>
|
||||
<h2>
|
||||
Interpreted mode performance improvements</h2>
|
||||
Igor Bukanov also made a number of improvements to interpreter mode performance.
|
||||
<br>
|
||||
<h2>
|
||||
JS/CORBA Adapter</h2>
|
||||
Matthias Radestock wrote a module that allows JavaScript code to interact
|
||||
with CORBA. See <a href="http://sourceforge.net/projects/jscorba">http://sourceforge.net/projects/jscorba</a>
|
||||
for more details.
|
||||
<br>
|
||||
<h2>
|
||||
Directory restructuring and Ant buildfile</h2>
|
||||
I've restructured the the Rhino directory and written an <a href="http://jakarta.apache.org/ant/index.html">Ant</a>
|
||||
buildfile. This should make building easier and more consistent with other
|
||||
open source Java projects.
|
||||
<br>
|
||||
<h2>
|
||||
FlattenedObject deprecated</h2>
|
||||
I wrote FlattenedObject to provide a means for dealing with JavaScript
|
||||
<br>objects in prototype chains. Where Scriptable defines the primitive
|
||||
<br>operations, FlattenedObject defines the aggregate operations of
|
||||
<br>manipulating properties that may be defined in an object or in an object
|
||||
<br>reachable by a succession of getPrototype calls.
|
||||
<p>However, I now believe that I designed FlattenedObject poorly. Perhaps
|
||||
<br>it should have been a clue that I was never satisfied with the name:
|
||||
if
|
||||
<br>it's hard to express the name of the object it may mean the function
|
||||
the
|
||||
<br>object is supposed to fulfill is not well defined either. The problem
|
||||
is
|
||||
<br>that it is inefficient since it requires an extra object creation,
|
||||
and
|
||||
<br>balky because of that extra level of wrapping.
|
||||
<p>So I've checked in changes that deprecate FlattenedObject. I've
|
||||
<br>introduced new static methods in ScriptableObject (thanks to
|
||||
<br>beard@netscape.com for the idea) that replace the functionality. These
|
||||
<br>methods perform the get, put, and delete operations on a Scriptable
|
||||
<br>object passed in without the overhead of creating a new object.
|
||||
<h2>
|
||||
WrapHandler interface</h2>
|
||||
Embeddings that wish to provide their own custom wrappings for Java objects
|
||||
may implement this interface and
|
||||
<br>call Context.setWrapHandler. See WrapHandler javadoc.
|
||||
<br>
|
||||
<h2>
|
||||
ClassOutput interface</h2>
|
||||
An interface embedders can implement in order to control the placement
|
||||
of generated class bytecodes. See the javadoc.
|
||||
<h3>
|
||||
|
||||
<hr WIDTH="100%"><br>
|
||||
<a href="index.html">back to top</a></h3>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,63 +0,0 @@
|
||||
<!DOCTYPE html PUBLIC "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
|
||||
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Change Log</title>
|
||||
</head>
|
||||
<body bgcolor="#ffffff">
|
||||
|
||||
<center>
|
||||
<h1> Change Log for Significant Rhino Changes</h1>
|
||||
</center>
|
||||
This is a log of significant changes since the release of Rhino 1.5 Release
|
||||
2.
|
||||
<p> </p>
|
||||
<h3> </h3>
|
||||
<h3>Serialization</h3>
|
||||
See the <a href="serialization.html">serialization documentation</a>
|
||||
.<br>
|
||||
<br>
|
||||
<h3>Class writer API changes</h3>
|
||||
Courtesy of Kemal Bayram.<br>
|
||||
<br>
|
||||
"The biggest change I've made is the replacement of ClassOutput with<br>
|
||||
ClassRepository that has the single method:<br>
|
||||
<br>
|
||||
public boolean storeClass(String className, byte[] classBytes,<br>
|
||||
|
||||
boolean isTopLevel) throws IOException;<br>
|
||||
<br>
|
||||
This interface allows any arbitary storage method, such as a<br>
|
||||
Hashtable/Map. In addition it also allows you to specify whether a<br>
|
||||
class should be loaded, via returning true or false. You can still
|
||||
use<br>
|
||||
ClassOutput as I've coded an internal wrapper.<br>
|
||||
<br>
|
||||
With this interface it has also been possible to strip out the file<br>
|
||||
saving code from Codegen and OptClassNameHelper. The file<br>
|
||||
saving code is now an inner class FileClassRepository in Context. As<br>
|
||||
a consequence of this I've stripped out some methods from ClassNameHelper.<br>
|
||||
The resulting code is much more cleaner then before hand and everything<br>
|
||||
still works as per usual.<br>
|
||||
<br>
|
||||
Other small additions are:<br>
|
||||
o Annonymous functions are now named class$1 instead of class1<br>
|
||||
o get/setClassName added to ClassNameHelper exposed in Context.
|
||||
"<br>
|
||||
<br>
|
||||
<h3>Bunches of bug fixes and optimizations from Igor Bukanov and others</h3>
|
||||
See the CVS logs<br>
|
||||
<h3>
|
||||
<hr width="100%"><br>
|
||||
<a href="index.html">back to top</a>
|
||||
</h3>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,201 +0,0 @@
|
||||
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html><head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Igor Bukanov">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Debug API changes</title>
|
||||
</head>
|
||||
|
||||
<body bgcolor="#ffffff">
|
||||
|
||||
<h2 align="center">Debug API changes in Rhino 1.5 Release 4</h2>
|
||||
<p>
|
||||
The main difference between the old and new API is that the application needs to implement both org.mozilla.javascript.debugger.Debugger and
|
||||
org.mozilla.javascript.debugger.DebugFrame interfaces to receive debug
|
||||
information during script execution. See the API documentation for these
|
||||
classes for details:
|
||||
<br>
|
||||
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/debug/DebugFrame.java">http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/debug/DebugFrame.java</a>
|
||||
<br><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/debug/Debugger.java">http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/debug/Debugger.java</a>
|
||||
</tt>
|
||||
<p>
|
||||
In addition the org.mozilla.javascript.debugger.DebuggableEngine interface and the getDebuggableEngine method in org.mozilla.javascript.Context are replaced by 3 Context methods: setDebugger, getDebugger and getDebuggerContextData to set/get debugger and its Context data in the current thread Context:<br>
|
||||
<tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/Context.java">http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/Context.java</a></tt>
|
||||
|
||||
<p>The following gives few examples how to update your current application to the new API.
|
||||
<p>
|
||||
1. Setting and querying a Debugger implementation
|
||||
<p>
|
||||
Old API:
|
||||
<pre>
|
||||
cx.getDebuggableEngine.setDebugger(debugger);
|
||||
cx.getDebuggableEngine.getDebugger();
|
||||
</pre>
|
||||
New API:
|
||||
<pre>
|
||||
cx.setDebugger(debugger);
|
||||
cx.getDebugger();
|
||||
</pre>
|
||||
|
||||
<p>
|
||||
2. Monitoring execution of each line in the script
|
||||
<p>
|
||||
Old implementation:
|
||||
<pre>
|
||||
public MyDebugger implement Debugger {
|
||||
|
||||
public void handleCompilationDone(Context cx,
|
||||
DebuggableScript fnOrScript,
|
||||
StringBuffer source)
|
||||
{
|
||||
}
|
||||
|
||||
void handleBreakpointHit(Context cx)
|
||||
{
|
||||
DebugFrame frame = cx.getDebuggableEngine().getFrame(0);
|
||||
System.out.println("New line:" + frame.getLineNumber());
|
||||
}
|
||||
|
||||
void handleExceptionThrown(Context cx, Object exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
...
|
||||
cx.getDebuggableEngine.setDebugger(new MyDebugger());
|
||||
cx.getDebuggableEngine.setBreakNextLine(true);
|
||||
</pre>
|
||||
|
||||
New implementation:
|
||||
<pre>
|
||||
public MyDebugger implement Debugger
|
||||
{
|
||||
public void handleCompilationDone(Context cx,
|
||||
DebuggableScript fnOrScript,
|
||||
StringBuffer source)
|
||||
{
|
||||
}
|
||||
|
||||
public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript)
|
||||
{
|
||||
return new MyDebugFrame();
|
||||
}
|
||||
}
|
||||
|
||||
class MyDebugFrame implements DebugFrame
|
||||
{
|
||||
public void onEnter(Context cx, Scriptable activation,
|
||||
Scriptable thisObj, Object[] args)
|
||||
{
|
||||
}
|
||||
|
||||
public void onExceptionThrown(Context cx, Throwable ex)
|
||||
{
|
||||
}
|
||||
|
||||
public void onExit(Context cx, boolean byThrow,
|
||||
Object resultOrException)
|
||||
{
|
||||
}
|
||||
|
||||
public void onLineChange(Context cx, int lineNumber)
|
||||
{
|
||||
System.out.println("New line:" + frame.getLineNumber());
|
||||
}
|
||||
}
|
||||
...
|
||||
cx.setDebugger(new MyDebugger());
|
||||
</pre>
|
||||
Note the in the new implementation the application can monitor function enter/exit by customizing enterFrame and onExit in the above code.
|
||||
<p>
|
||||
3. Breakpoint handling
|
||||
<p>
|
||||
Old implementation:
|
||||
<pre>
|
||||
public MyDebugger implement Debugger {
|
||||
|
||||
public void handleCompilationDone(Context cx, DebuggableScript fnOrScript,
|
||||
StringBuffer source)
|
||||
{
|
||||
int breakpointLine = ...;
|
||||
fnOrScript.placeBreakpoint(breakpointLine);
|
||||
}
|
||||
|
||||
void handleBreakpointHit(Context cx) {
|
||||
DebugFrame frame = cx.getDebuggableEngine().getFrame(0);
|
||||
System.out.println("Breakpoint hit: "+frame.getSourceName()+":"+frame.getLineNumber());
|
||||
}
|
||||
|
||||
void handleExceptionThrown(Context cx, Object exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
...
|
||||
cx.getDebuggableEngine.setDebugger(new MyDebugger());
|
||||
</pre>
|
||||
|
||||
New implementation:
|
||||
<pre>
|
||||
public MyDebugger implement Debugger
|
||||
{
|
||||
public void handleCompilationDone(Context cx,
|
||||
DebuggableScript fnOrScript,
|
||||
StringBuffer source)
|
||||
{
|
||||
}
|
||||
|
||||
public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript)
|
||||
{
|
||||
return new MyDebugFrame(fnOrScript);
|
||||
}
|
||||
}
|
||||
|
||||
class MyDebugFrame implements DebugFrame
|
||||
{
|
||||
DebuggableScript fnOrScript;
|
||||
|
||||
MyDebugFrame(DebuggableScript fnOrScript)
|
||||
{
|
||||
this.fnOrScript = fnOrScript;
|
||||
}
|
||||
|
||||
public void onEnter(Context cx, Scriptable activation,
|
||||
Scriptable thisObj, Object[] args)
|
||||
{
|
||||
System.out.println("Frame entered");
|
||||
}
|
||||
|
||||
public void onLineChange(Context cx, int lineNumber)
|
||||
{
|
||||
if (isBreakpoint(lineNumber)) {
|
||||
System.out.println("Breakpoint hit: "+fnOrScript.getSourceName()+":"+lineNumber);
|
||||
}
|
||||
}
|
||||
|
||||
public void onExceptionThrown(Context cx, Throwable ex)
|
||||
{
|
||||
}
|
||||
|
||||
public void onExit(Context cx, boolean byThrow,
|
||||
Object resultOrException)
|
||||
{
|
||||
System.out.println("Frame exit, result="+resultOrException);
|
||||
}
|
||||
|
||||
private boolean isBreakpoint(int lineNumber)
|
||||
{
|
||||
...
|
||||
}
|
||||
}
|
||||
...
|
||||
cx.setDebugger(new MyDebugger());
|
||||
</pre>
|
||||
|
||||
Here debugger during execution needs to decide if a particular line has breakpoint on it set or not during script execution, not at the moment of script initialization.
|
||||
|
||||
<p>See also Rhino Debugger that fully explore the new API:<br><tt><a href="http://lxr.mozilla.org/mozilla/source/js/rhino/toolsrc/org/mozilla/javascript/tools/debugger/Main.java">http://lxr.mozilla.org/mozilla/source/js/rhino/toolsrc/org/mozilla/javascript/tools/debugger/Main.java</a></tt>. The debugger changes includes support for debugging eval and Function scripts and loading script sources from their URL if debugger was not installed during scripts initialization.
|
||||
|
||||
<hr width="100%"><br>
|
||||
<a href="index.html">back to top</a></h3>
|
||||
|
||||
|
||||
</body></html>
|
||||
@@ -1,217 +0,0 @@
|
||||
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en"><html><head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java"><title>Change Log</title></head>
|
||||
|
||||
<body bgcolor="#ffffff">
|
||||
|
||||
<h1 align="center">
|
||||
Rhino Change Log</h1>
|
||||
|
||||
This is a log of changes since the release of Rhino 1.5 Release 3.
|
||||
|
||||
<h3>Rhino debug API changes</h3>
|
||||
|
||||
A new, incompatible Rhino debug API gives an option to monitor
|
||||
entering/leaving of script functions while decreasing the amount of code to
|
||||
implement the API in the Rhino core. Details are available <a href="rhino15R4-debugger.html">here</a>. With the new API <a href="debugger.html">Rhino Debugger</a> provides options to break on function enter/exit, can debug scripts defined by eval and Function construction and scripts loaded prior the debugger were started.
|
||||
|
||||
<h3>WrapFactory introduced, WrapHandler deprecated</h3>
|
||||
A design flaw in the WrapHandler interface (a call to a Java contructor from
|
||||
JavaScript would result in a call to wrap the result, which would then be
|
||||
cast to a Scriptable) inspired the deprecation of that interface and the
|
||||
introduction of a new class, WrapFactory, that contains a new method called
|
||||
on the result of a constructor call and can be customized by application if necessary.
|
||||
<p>
|
||||
In addition, WrapFactory has the new <tt>setJavaPrimitiveWrap</tt> method to control if instances of Java <tt>String</tt> and <tt>Number</tt> class should be wrapped to special script objects as any other Java objects so a script can access any method <tt>String</tt> and <tt>Number</tt>, or they should be converted to JavaScript primitive strings and numbers.
|
||||
|
||||
<h3>New security interfaces</h3>
|
||||
<p>
|
||||
Igor Bukanov contributed a new security implementation that allows integration with Java2 security model and prevents scripts to escape the security sandbox via eval/Function schemes.
|
||||
<p>
|
||||
Due to this changes SecuritySupport interface is replaced by ClassShutter and SecurityController, where ClassShutter controls which classes are visible to scripts via LiveConnect and SecurityController provides permission management. For compatibility SecuritySupport is still available as a deprecated interface but only its visibleToScripts method is used as an alias for ClassShutter.visibleToScripts. See API documentation for new classes for details.
|
||||
<p>
|
||||
An implementation of SecurityController that uses java policy settings to restrict script permissions based on its URL is available with Rhino shell. See the <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/toolsrc/org/mozilla/javascript/tools/shell/JavaPolicySecurity.java">JavaPolicySecurity</a> source for details. To activate it, set the <tt>rhino.use_java_policy_security</tt> system property to true when invoking Rhino shell together with installing a security manager.
|
||||
|
||||
<h3>Serialization chages</h3>
|
||||
Due to changes in Rhino implementation and bug fixes in serialization support runtime data serialized in Rhino 1.5 Release 3 can not be read back in the Release 4.
|
||||
|
||||
<h3>Regular expressions improvements</h3>
|
||||
Roger Lawrence provided new regular expressions implementation which fully confirms to EcmaScript 262 standard and faster.
|
||||
|
||||
<h3>Scripting of classes from any class loader</h3>
|
||||
|
||||
Christopher Oliver contributed code to allow to use the <tt>Packages</tt> object as a constructor taking a class loader argument so a script can access classes defined by that class loader. For example, to access classes from foo.jar file in the current directory, the following can be used:
|
||||
<pre>
|
||||
// create class loader
|
||||
var loader = new java.net.URLClassLoader([new java.net.URL("file:./foo.jar")]);
|
||||
// create its LiveConnect wrapper
|
||||
var fooJar = new Packages(loader);
|
||||
// create an instance of the class For from foo.jar
|
||||
var obj = new fooJar.Foo(1, 2, 3);
|
||||
obj.someMethod();
|
||||
</pre>
|
||||
|
||||
<h3>Shell function to run external processes.</h3>
|
||||
A new <tt>runCommand</tt> function is added to <a href="shell.html">Rhino Shell</a> to run external priocesses. For details, see JavaDoc for <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/toolsrc/org/mozilla/javascript/tools/shell/Global.java">org.mozilla.javascript.tools.shell.Global#runCommand</a>.
|
||||
|
||||
<h3>Resolved Bugzilla reports</h3>
|
||||
|
||||
The following Rhino reports in <a href="http://bugzilla.mozilla.org/">Bugzilla</a> where resolved for Rhino 1.5 Release 4.
|
||||
<p>
|
||||
<a href="http://bugzilla.mozilla.org/show_bug.cgi?id=61579">61579</a> -
|
||||
context.decompileScript doesn't work.
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=72021">72021</a> -
|
||||
The ScriptRuntime class tries to convert even the String values to JavaNativeObject
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=83051">83051</a> -
|
||||
A function defined under a with block can't be invoked outside it
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=104089">104089</a> -
|
||||
Cannot reattach context to its thread because of the bug in Context class
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=105438">105438</a> -
|
||||
SourceName and lineNumbers of syntax errors in Javascript files not dispalyed.
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=106548">106548</a> -
|
||||
/^.*?$/ will not match anything
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=114583">114583</a> -
|
||||
script compile/decompile bug
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=114969">114969</a> -
|
||||
[], [^] are valid RegExp conditions
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=115717">115717</a> -
|
||||
java.lang.ArrayIndexOutOfBoundsException on with/try/finally
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=120194">120194</a> -
|
||||
JS toInt32(x) conversion doesn't match ECMAScript definition
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=122167">122167</a> -
|
||||
string.replace() placeholder '$1' not working
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=123439">123439</a> -
|
||||
Backreferences /(a)? etc./ must hold |undefined| if not used
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=124508">124508</a> -
|
||||
regexp.lastIndex should be integer-valued double, not uint32
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=124900">124900</a> -
|
||||
arguments object storing duplicate parameter values
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=125562">125562</a> -
|
||||
Regexp performance improvement
|
||||
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=126317">126317</a> -
|
||||
Crash on re.exec(str) if re.lastIndex set to certain values
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=126722">126722</a> -
|
||||
(undefined === null) evaluating to true in Rhino compiled mode
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=128468">128468</a> -
|
||||
java.io.NotSerializableException: org.mozilla.javascript.NativeError
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=129365">129365</a> -
|
||||
Incorrect licensing in dtoa.java
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=132217">132217</a> -
|
||||
delete on global function should not delete the function
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=136893">136893</a> -
|
||||
Rhino treatment of |for(i in undefined)|, |for(i in null)|
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=137181">137181</a> -
|
||||
delete on an arguments[i] not working correctly
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=145791">145791</a> -
|
||||
ECMA conformance: Function.prototype.apply(), Function.prototype.call()
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=149285">149285</a> -
|
||||
Complier does not report the correct line number on SyntaxError:Invalid assignment left-hand side.
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=151337">151337</a> -
|
||||
EcmaError.getLineSource() returns 0x0 characters.
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=153223">153223</a> -
|
||||
New RegExp engine in Rhino
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=154693">154693</a> -
|
||||
Interpreted mode doesn't grok different functions on different objects
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=156510">156510</a> -
|
||||
for (i in undefined) {} should not throw TypeError
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=157196">157196</a> -
|
||||
ScriptableObject needs custom serialization implementation
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=157509">157509</a> -
|
||||
No error on invalid usage of \ in identifiers
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=158159">158159</a> -
|
||||
Should Rhino support octal escape sequences in regexps?
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=159334">159334</a> -
|
||||
The javascript functions size is limited by a bug
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=164947">164947</a> -
|
||||
Debugging unique.js produce a stack trace and erratic results
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=166530">166530</a> -
|
||||
ClassCostException in FunctionObject static initializer
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=169830">169830</a> -
|
||||
Array.concat(function) doesn't add function to the array
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=173180">173180</a> -
|
||||
Rhino UTF-8 decoder accepts overlong sequences
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=173906">173906</a> -
|
||||
Dynamic scope not working correctly with optimzation level >= 1
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=175383">175383</a> -
|
||||
ArrayIndexOutOfBoundsException in string.replace()
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=177314">177314</a> -
|
||||
Rhino should allow '\400' to mean ' 0'
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=179068">179068</a> -
|
||||
String literals in Rhino are limited to 64K
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=179366">179366</a> -
|
||||
--> after whitespace after line start should mean comments to line end
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=181654">181654</a> -
|
||||
Calling toString for an object derived from the Error class throws TypeError
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=181834">181834</a> -
|
||||
wrong scope used for inner functions when compiling functions with dynamic scopes (interpreted only)
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=181909">181909</a> -
|
||||
some regression tests for Error invalid
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=182028">182028</a> -
|
||||
Calling has() in get() of a ScriptableObject causes getter function to not be called
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=184107">184107</a> -
|
||||
with(...) { function f ...} should set f in the global scope
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=184111">184111</a> -
|
||||
ArrayOutOfBounds Exception thrown when using Rhino Javascript Debugger
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=185165">185165</a> -
|
||||
Decompilation of "\\" gives broken "\"
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=189183">189183</a> -
|
||||
Debugger source frame window layering fix
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=189898">189898</a> -
|
||||
Broken String.replace: "XaXY".replace("XY", "--") gives --aXY
|
||||
|
||||
<hr width="100%"><br>
|
||||
<a href="index.html">back to top</a></h3>
|
||||
|
||||
</body></html>
|
||||
@@ -1,41 +0,0 @@
|
||||
<!DOCTYPE doctype PUBLIC "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Igor Bukanov">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Rhino 1.5 Release 4.1 Change Log</title>
|
||||
</head>
|
||||
|
||||
<body bgcolor="#ffffff">
|
||||
|
||||
<h1 align="center">Rhino 1.5 Release 4.1 Change Log</h1>
|
||||
|
||||
1.5R4.1 is a bug fix release to address mostly regressions from 1.5R3 found in 1.5R4. The only visible API change compared with 1.5R4 is two new methods in <tt>org.mozilla.javascript.Context</tt>, <tt>getApplicationClassLoader()</tt> and <tt>setApplicationClassLoader(ClasssLoader)</tt>. They allow to control the class loader Rhino uses when accessing application classes.
|
||||
<p>
|
||||
For differences between 1.5R4 and 1.5R3, see <a href="rhino15R4.html">1.5R4 change log</a>.
|
||||
|
||||
<h3>Resolved Bugzilla reports</h3>
|
||||
|
||||
The following Rhino reports in <a href="http://bugzilla.mozilla.org/">Bugzilla</a> where resolved for Rhino 1.5 Release 4.
|
||||
<p>
|
||||
<a href="http://bugzilla.mozilla.org/show_bug.cgi?id=96270">96270</a> -
|
||||
Unable to create java objects from within a javascript.
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=193168">193168</a> -
|
||||
Rhino debugger in v1.5R4 fails to update script source when a script is reloaded.
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=193555">193555</a> -
|
||||
1.5R4 regression: function expression has no access to its name.
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=196017">196017</a> -
|
||||
1.5R4 regression: script can not find classes on some versions of JDK.
|
||||
|
||||
<br><a href="http://bugzilla.mozilla.org/show_bug.cgi?id=200551">200551</a> -
|
||||
JavaAdapter not loading a class if js.jar installed in jre/lib/ext directory.
|
||||
|
||||
|
||||
<hr width="100%"><br>
|
||||
<a href="index.html">back to top</a></h3>
|
||||
|
||||
</body></html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 6.6 KiB |
@@ -1,138 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (WinNT; U) [Netscape]">
|
||||
<title>JavaScript Runtime</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
The JavaScript Runtime</h1></center>
|
||||
|
||||
<h3>
|
||||
Interpretation</h3>
|
||||
Beginning with Rhino 1.4 Release 2, an interpretive mode is supported.
|
||||
When scripts are compiled in interpretive mode, an internal representation
|
||||
of the compiled form is created and stored rather than generating a Java
|
||||
class. Execution proceeds by evaluating this compiled form using support
|
||||
routines in Rhino.
|
||||
<h3>
|
||||
Compilation to Java Bytecodes</h3>
|
||||
For improved performance, Rhino may compile JavaScript scripts to Java
|
||||
bytecodes. The generated bytecodes in turn depend upon runtime support
|
||||
routines. Each JavaScript script or function is compiled to a separate
|
||||
class.
|
||||
<p>Compilation of JavaScript source to class files is supported. It is
|
||||
possible to specify the class files as well as the packages to generate
|
||||
into.
|
||||
<h3>
|
||||
Types and Values</h3>
|
||||
There are six fundamental types in JavaScript. These types are implemented
|
||||
with the following Java types and values:
|
||||
<br>
|
||||
<br>
|
||||
<center><table BORDER COLS=2 WIDTH="75%" >
|
||||
<tr>
|
||||
<td><i>JavaScript fundamental type</i></td>
|
||||
|
||||
<td><i>Java type</i></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Undefined</td>
|
||||
|
||||
<td>A singleton object defined by <tt>Context.getUndefinedType()</tt></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Null</td>
|
||||
|
||||
<td><tt>null</tt></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Boolean</td>
|
||||
|
||||
<td><tt>java.lang.Boolean</tt></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Number</td>
|
||||
|
||||
<td><tt>java.lang.Number</tt>, that is, any of <tt>java.lang.Byte</tt>,<tt>
|
||||
java.lang.Short</tt>,<tt> java.lang.Integer</tt>,<tt> java.lang.Float</tt>,
|
||||
or <tt>java.lang.Double. Not java.lang.Long, since a double representation
|
||||
of a long may lose precision.</tt></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>String</td>
|
||||
|
||||
<td><tt>java.lang.String</tt></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Object</td>
|
||||
|
||||
<td><tt>org.mozilla.javascript.Scriptable</tt></td>
|
||||
</tr>
|
||||
</table></center>
|
||||
|
||||
<p>In addition, ECMA refers to objects that implement [[Call]] as functions.
|
||||
These object types are represented by implementing the Function interface.
|
||||
<p>Since JavaScript is a dynamically typed language, the static Java type
|
||||
of a JavaScript value is <tt>java.lang.Object</tt>.
|
||||
<p>The behavior of the JavaScript engine is undefined if a value of any
|
||||
type other than the ones described above is introduced into JavaScript.
|
||||
(This caveat does not apply to scripts that use LiveConnect; the Java values
|
||||
are wrapped and unwrapped as appropriate to conform to the above type constraints.)
|
||||
<br>
|
||||
<h3>
|
||||
Property Access</h3>
|
||||
Properties in JavaScript objects may be accessed using either string or
|
||||
numeric identifiers. Conceptually, all accessors are converted to strings
|
||||
in order to perform the lookup of the property in the object. However,
|
||||
this is not the implementation used in practice because a number to string
|
||||
conversion is too expensive to be performed on every array access.
|
||||
<p>Instead, every property accessor method in <a href="org/mozilla/javascript/Scriptable.html">Scriptable</a>
|
||||
(<tt>has</tt>, <tt>get</tt>, <tt>set</tt>, <tt>remove</tt>, <tt>getAttributes</tt>,
|
||||
and <tt>setAttributes</tt>) has overloaded forms that take either a <tt>String</tt>
|
||||
or an <tt>int</tt> argument. It is the responsibility of the caller to
|
||||
invoke the appropriate overloaded form. For example, evaluating the expression
|
||||
<tt>obj["3"]</tt>
|
||||
will invoke the get(int, Scriptable) method even though the property name
|
||||
was presented in the script as a string. Similarly, values of numbers that
|
||||
do not fix in integers (like 1.1 and 0x100000000) must be converted to
|
||||
strings.
|
||||
<br>
|
||||
<h3>
|
||||
Defining Host Objects</h3>
|
||||
Host objects are JavaScript objects that provide special access to the
|
||||
host environment. For example, in a browser environment, the Window and
|
||||
Document objects are host objects.
|
||||
<p>The easiest way to define new host objects is by using <a href="org/mozilla/javascript/ScriptableObject.html#defineClass(org.mozilla.javascript.Scriptable, java.lang.Class)">ScriptableObject.defineClass()</a>.
|
||||
This method defines a set of JavaScript objects using a Java class. Several
|
||||
of the <a href="examples.html">examples</a> define host objects this way.
|
||||
<p>If the services provided by defineClass are insufficient, try other
|
||||
methods of
|
||||
<a href="org/mozilla/javascript/ScriptableObject.html">ScriptableObject</a>
|
||||
and
|
||||
<a href="org/mozilla/javascript/FunctionObject.html">FunctionObject</a>,
|
||||
such as <tt>defineProperty</tt> and <tt>defineFunctionProperties</tt>.
|
||||
<br>
|
||||
<br>
|
||||
<h3>
|
||||
Contexts and Threads</h3>
|
||||
Every thread that executes JavaScript must have an associated Context.
|
||||
Multiple threads (with multiple associated Contexts) may act upon the same
|
||||
set of objects. Any host objects that are defined are responsible for any
|
||||
sychronization required to run safely from multiple threads.
|
||||
<br>
|
||||
<p>
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="index.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 80 KiB |
@@ -1,194 +0,0 @@
|
||||
<!DOCTYPE html PUBLIC "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
|
||||
<meta name="GENERATOR" content="Mozilla/4.72 [en]C-NSCP (WinNT; U) [Netscape]">
|
||||
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Scopes and Contexts</title>
|
||||
</head>
|
||||
<body bgcolor="#ffffff">
|
||||
|
||||
<script src="owner.js"></script>
|
||||
<center>
|
||||
<h1> Scopes and Contexts</h1>
|
||||
</center>
|
||||
|
||||
<script>document.write(owner());</script> <br>
|
||||
<script>
|
||||
var d = new Date(document.lastModified);
|
||||
document.write((d.getMonth()+1)+"/"+d.getDate()+"/"+d.getFullYear());
|
||||
document.write('<br>');
|
||||
</script>
|
||||
<center>
|
||||
<hr width="100%"></center>
|
||||
|
||||
<p>Before using Rhino in a concurrent environment, it is important to understand
|
||||
the distinction between Contexts and scopes. Both are required to execute
|
||||
scripts, but they play different roles. Simple embeddings of Rhino probably
|
||||
won't need any of the information here, but more complicated embeddings can
|
||||
gain performance and flexibility from the techniques described below. <br>
|
||||
</p>
|
||||
<h2> Contexts</h2>
|
||||
The Rhino Context object is used to store thread-specific information about
|
||||
the execution environment. There should be one and only one Context associated
|
||||
with each thread that will be executing JavaScript.
|
||||
<p>To associate the current thread with a Context, simply call the <tt>enter</tt>
|
||||
method of Context: </p>
|
||||
<pre>
|
||||
Context cx = Context.enter();
|
||||
</pre>
|
||||
Once you are done with execution, simply exit the Context:
|
||||
<pre>
|
||||
Context.exit();
|
||||
</pre>
|
||||
These calls will work properly even if there is already a Context associated
|
||||
with the current thread. That context will be returned and an internal counter
|
||||
incremented. Only when the counter reaches zero will it be disassociated from
|
||||
the thread.
|
||||
<p>Remember to put the <tt>exit()</tt> call in a <tt>finally</tt> block if
|
||||
you're executing code that could throw an exception. <br>
|
||||
</p>
|
||||
<h2> Scopes</h2>
|
||||
A scope is a set of JavaScript objects. Execution of scripts requires a scope
|
||||
for top-level script variable storage as well as a place to find standard
|
||||
objects like <tt>Function</tt> and <tt>Object</tt>.
|
||||
<p>It's important to understand that a scope is independent of the Context
|
||||
that created it. You can create a scope using one Context and then evaluate
|
||||
a script using that scope and another Context (either by exiting the current
|
||||
context and entering another, or by executing on a different thread). You
|
||||
can even execute scripts on multiple threads simultaneously in the same scope.
|
||||
Rhino guarantees that accesses to properties of JavaScript objects are atomic
|
||||
across threads, but doesn't make any more guarantees for scripts executing
|
||||
in the same scope at the same time. If two scripts use the same scope simultaneously,
|
||||
the scripts are responsible for coordinating any accesses to shared variables.
|
||||
</p>
|
||||
<p>A top-level scope is created by calling <tt>Context.initStandardObjects</tt>
|
||||
to create all the standard objects: </p>
|
||||
<pre>
|
||||
ScriptableObject scope = cx.initStandardObjects();
|
||||
</pre>
|
||||
The easiest way to embed Rhino is just to create a new scope this way whenever
|
||||
you need one. However, <tt>initStandardObjects</tt> is an expensive method
|
||||
to call and it allocates a fair amount of memory. We'll see below that there
|
||||
are ways to share a scope created this way among multiple scopes and threads.
|
||||
<br>
|
||||
|
||||
<h2> Name Lookup</h2>
|
||||
So how are scopes used to look up names? In general, variables are looked
|
||||
up by starting at the current variable object (which is different depending
|
||||
on what code is being executed in the program), traversing its prototype chain,
|
||||
and then traversing the parent chain. In the diagram below, the order in
|
||||
which the six objects are traversed is indicated.
|
||||
<center>
|
||||
<p><img src="lookup.gif" height="194" width="500">
|
||||
<br>
|
||||
<i><font size="-1">Order of lookups in a two-deep scope chain with prototypes.</font></i></p>
|
||||
</center>
|
||||
|
||||
<p>For a more concrete example, let's consider the following script: </p>
|
||||
<blockquote><tt>var g = 7;</tt> <br>
|
||||
<tt>function f(a) {</tt> <br>
|
||||
<tt> var v = 8;</tt> <br>
|
||||
<tt> x = v + a;</tt> <br>
|
||||
<tt>}</tt> <br>
|
||||
<tt>f(6);</tt></blockquote>
|
||||
We have a top-level variable <tt>g</tt>, and the call to <tt>f</tt> will
|
||||
create a new top-level variable <tt>x</tt>. All top-level variables are properties
|
||||
of the scope object. When we start executing <tt>f</tt>, the scope chain
|
||||
will start with the function's activation object and will end with the top-level
|
||||
scope (see diagram below). The activation object has two properties, 'a'
|
||||
for the argument, and 'v' for the variable. The top-level scope has properties
|
||||
for the variable <tt>g</tt> and the function <tt>f</tt>.
|
||||
<center>
|
||||
<p><img src="scopes.gif" height="496" width="820">
|
||||
<br>
|
||||
<i><font size="-1">An example scope chain for a simple script.</font></i></p>
|
||||
</center>
|
||||
|
||||
<p>When the statement <tt>x = v + a;</tt> is executed, the scope chain is
|
||||
traversed looking for a 'x' property. When none is found, a new property 'x'
|
||||
is created in the top-level scope. </p>
|
||||
<h2> Sharing Scopes</h2>
|
||||
JavaScript is a language that uses delegation rather than traditional class-based inheritance. This is a large topic in itself, but for our purposes it gives us an easy way to share a set of read-only variables across multiple scopes.
|
||||
|
||||
To do this we set an object's prototype. When accessing a property of an object
|
||||
in JavaScript, the object is first searched for a property with the given
|
||||
name. If none is found, the object's prototype is searched. This continues
|
||||
until either the object is found or the end of the prototype chain is reached.
|
||||
<p>So to share information across multiple scopes, we first create the object
|
||||
we wish to share. Typically this object will have been created with <tt>initStandardObjects</tt>
|
||||
and may also have additional objects specific to the embedding. Then all
|
||||
we need to do is create a new object and call its <tt>setPrototype</tt> method
|
||||
to set the prototype to the shared object, and the parent of the new scope
|
||||
to null:
|
||||
<pre> Scriptable newScope = cx.newObject(sharedScope);
|
||||
newScope.setPrototype(sharedScope);
|
||||
newScope.setParentScope(null);
|
||||
</pre>
|
||||
The call to <tt>newObject</tt> simply creates a new JavaScript object with
|
||||
no properties. It uses the <tt>sharedScope</tt> passed in to initialize the
|
||||
prototype with the standard <tt>Object.prototype</tt> value.
|
||||
<p>We can now use <tt>newScope</tt> as a scope for calls to evaluate scripts.
|
||||
Let's call this scope the <i>instance scope</i>. Any top-level functions or
|
||||
variables defined in the script will end up as properties of the instance
|
||||
scope. Uses of standard objects like <tt>Function</tt>, <tt>String</tt>, or
|
||||
<tt>RegExp</tt> will find the definitions in the shared scope. Multiple
|
||||
instance scopes can be defined and have their own variables for scripts yet
|
||||
share the definitions in the shared scope. These multiple instance scopes
|
||||
can be used concurrently. <br>
|
||||
</p>
|
||||
<h2>Sealed shared scopes</h2>
|
||||
<p>The ECMAScript standard defines that scripts can add properties to all standard library objects and in many cases it is also possible to change or delete their properties as well. Such behavior may not be suitable with shared scopes since if a script by mistake adds a property to a library object from the shared scope, that object would not be garbage collected until there re active references to the shared scope potentially leading to memory leaks. In addition if a script alters some of the standard objects, the library may not work properly for other scripts. Such bugs are hard to debug and to remove a possibility for them to occur one can use seal the shared scope and all its objects.
|
||||
<p>
|
||||
A notion of a sealed object is a JavaScript extension supported by Rhino and it means that properties can not be added/deleted to the object and the existing object properties can not be changed. Any attempt to modify sealed object throws an exception. To seal all objects in the standard library pass <tt>true</tt> for the sealed argument when calling <tt>Context.initStandardObjects(ScriptableObject, boolean)</tt>:
|
||||
<pre> ScriptableObject sealedSharedScope = cx.initStandardObjects(null, true);</pre>
|
||||
This seals only all standard library objects, it does not seal the shared scope itself thus after calling <tt>initStandardObjects</tt>, <tt>sealedSharedScope</tt> cab be farther populated with application-specific objects and functions. Then after a custom initialization is done, one can seal the shared scope by calling <tt>ScriptableObject.sealObject()</tt>:
|
||||
<pre> sealedSharedScope.sealObject();</pre>
|
||||
|
||||
Note that currently one needs to explicitly seal any additional properties he adds to the sealed shared scope since although after calling <tt>sealedSharedScope.sealObject();</tt> it would no be possible to set the additional properties to different values, one still would be able to alter the objects themselves.
|
||||
|
||||
<h2> Dynamic Scopes</h2>
|
||||
There's one problem with the setup outlined above. Calls to functions in
|
||||
JavaScript use <i>static scope</i>, which means that variables are first looked
|
||||
up in the function and then, if not found there, in the lexically enclosing
|
||||
scope. This causes problems if functions you define in your shared scope
|
||||
need access to variables you define in your instance scope.
|
||||
<p>With Rhino 1.5, it is possible to compile functions to use <i>dynamic
|
||||
scope</i>. With dynamic scope, functions look at the top-level scope of the
|
||||
calling function rather than their lexical scope. So we can store information
|
||||
that varies across scopes in the instance scope yet still share functions
|
||||
that manipulate that information reside in the shared scope. </p>
|
||||
<p>The <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/DynamicScopes.java">
|
||||
DynamicScopes example</a>
|
||||
illustrates all the points discussed above. <br>
|
||||
<br>
|
||||
</p>
|
||||
<h2> More on Scopes</h2>
|
||||
The key things to determine in setting up scopes for your application are
|
||||
<br>
|
||||
(1) What scope should global variables be created in when your script executes
|
||||
an assignment to an undefined variable, and <br>
|
||||
(2) What variables should your script have access to when it references a
|
||||
variable?
|
||||
<p>The answer to (1) determines which scope should be the ultimate parent
|
||||
scope: Rhino follows the parent chain up to the top and places the variable
|
||||
there. After you've constructed your parent scope chain, the answer to question
|
||||
(2) may indicate that there are additional scopes that need to be searched
|
||||
that are not in your parent scope chain. You can add these as prototypes
|
||||
of scopes in your parent scope chain. When Rhino looks up a variable, it
|
||||
starts in the current scope, walks the prototype chain, then goes to the
|
||||
parent scope and its prototype chain, until there are no more parent scopes
|
||||
left. <br>
|
||||
</p>
|
||||
<h3>
|
||||
<hr width="100%"><br>
|
||||
<a href="index.html">back to top</a>
|
||||
</h3>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 53 B |
@@ -1,219 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.7 [en] (WinNT; U) [Netscape]">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Scripting Java</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
<script src="owner.js"></script>
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
Scripting Java</h1></center>
|
||||
<script>document.write(owner());</script>
|
||||
|
||||
<br><script>
|
||||
var d = new Date(document.lastModified);
|
||||
document.write((d.getMonth()+1)+"/"+d.getDate()+"/"+d.getFullYear());
|
||||
document.write('<br>');
|
||||
</script>
|
||||
|
||||
<center>
|
||||
<hr WIDTH="100%"></center>
|
||||
|
||||
<p>It's possible to use Rhino just for scripting Java. You don't have to
|
||||
write any additional Java code; just use the existing Rhino shell and then
|
||||
make calls into Java.
|
||||
<br>
|
||||
<h2>
|
||||
Rhino Shell</h2>
|
||||
The Rhino shell allows you to run scripts from files or interactively at
|
||||
a command line.
|
||||
<p>If you download the zip file for rhino, it will contain a single JAR
|
||||
file, <tt>js.jar</tt>. If you add the JAR file to your class path, you
|
||||
can start the Rhino shell using the command
|
||||
<pre> java org.mozilla.javascript.tools.shell.Main</pre>
|
||||
or if you have Java 2 (JDK 1.2 or greater), you can avoid changing your classpath
|
||||
and simply use the command
|
||||
<pre> java -jar js.jar</pre>
|
||||
Unfortunately the <tt>-jar</tt> option to <tt>java</tt> will overwrite
|
||||
your existing classpath. The shell's interactive mode is a good way to
|
||||
begin exploring Rhino.
|
||||
<p><i>Note: Earlier versions of Rhino have two JAR files, js.jar and jstools.jar,
|
||||
and don't support the -jar option. Both JAR files must be added to the
|
||||
class path to start the shell</i>.
|
||||
<p>You can execute a JavaScript file by putting the file name as an argument
|
||||
to the shell class:
|
||||
<pre> java org.mozilla.javascript.tools.shell.Main myScript.js</pre>
|
||||
There are a number of options for evaluating scripts using the shell. See
|
||||
the <a href="http://www.mozilla.org/rhino/shell.html">command description</a>
|
||||
for more information.
|
||||
<br>
|
||||
<h2>
|
||||
LiveConnect: Communicating with Java from JavaScript</h2>
|
||||
If you are planning to script Java using Rhino, you'll want to use LiveConnect,
|
||||
which allows you to create Java classes and call Java methods from within
|
||||
JavaScript. For example, here's a log from an interactive session. If you
|
||||
type it in, you'll see a window with a button filling it.
|
||||
<center>
|
||||
<p><img SRC="scriptjavaframe.jpg" height=100 width=200>
|
||||
<br><i><font size=-1>A Java frame created from the Rhino shell.</font></i></center>
|
||||
|
||||
<pre>$ java org.mozilla.javascript.tools.shell.Main
|
||||
js> importPackage(java.awt);
|
||||
js> frame = new Frame("JavaScript")
|
||||
java.awt.Frame[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,resizable,title=JavaScript]
|
||||
js> frame.show()
|
||||
js> frame.setSize(new Dimension(200,100))
|
||||
js> button = new Button("OK")
|
||||
java.awt.Button[button0,0,0,0x0,invalid,label=OK]
|
||||
js> frame.add(button)
|
||||
java.awt.Button[button0,0,0,0x0,invalid,label=OK]
|
||||
js> frame.show()
|
||||
js> quit()
|
||||
$</pre>
|
||||
If you wish to load classes from JavaScript that aren't in the <tt>java</tt>
|
||||
package, you'll need to prefix the package name with "<tt>Packages.</tt>".
|
||||
For example:
|
||||
<pre>$ java org.mozilla.javascript.tools.shell.Main
|
||||
js> cx = Packages.org.mozilla.javascript.Context.enter()
|
||||
org.mozilla.javascript.Context@25980b44
|
||||
js> cx.evaluateString(this, "3+2", null, 0, null)
|
||||
5.0
|
||||
js> quit()
|
||||
$</pre>
|
||||
|
||||
<h2>
|
||||
Accessing JavaBean Properties</h2>
|
||||
Java classes can define JavaBean properties using getter and setter methods.
|
||||
For example, the following class defines two properties:
|
||||
<p><tt>public class Me {</tt>
|
||||
<br><tt> public int getAge() { return age; }</tt>
|
||||
<br><tt> public void setAge(int anAge) { age = anAge;
|
||||
}</tt>
|
||||
<br><tt> public String getSex() { return "male"; }</tt>
|
||||
<br><tt> private int age;</tt>
|
||||
<br><tt>};</tt>
|
||||
<p>The two properties defined are <i>age</i> and <i>sex</i>. The <i>sex</i>
|
||||
property is read-only: it has no setter.
|
||||
<p>Using Rhino we can access the bean properties as if they where JavaScript
|
||||
properties. We can also continue to call the methods that define the property.
|
||||
<p><tt>js> me = new Packages.Me();</tt>
|
||||
<br><tt>Me@93</tt>
|
||||
<br><tt>js> me.getSex()</tt>
|
||||
<br><tt>male</tt>
|
||||
<br><tt>js> me.sex</tt>
|
||||
<br><tt>male</tt>
|
||||
<br><tt>js> me.age = 33;</tt>
|
||||
<br><tt>33</tt>
|
||||
<br><tt>js> me.age</tt>
|
||||
<br><tt>33</tt>
|
||||
<br><tt>js> me.getAge()</tt>
|
||||
<br><tt>33</tt>
|
||||
<br><tt>js></tt>
|
||||
<p>Since the <i>sex</i> property is read-only, we are not allowed to write
|
||||
to it.
|
||||
<p><i>Note: JavaBean reflection is not available in versions of Rhino before
|
||||
1.5.</i>
|
||||
<br><tt></tt>
|
||||
<h2>
|
||||
Importing Java Classes and Packages</h2>
|
||||
Above we saw the use of the <tt>importPackage</tt> function to import all
|
||||
the classes from a particular Java package. There is also <tt>importClass</tt>,
|
||||
which imports a single class:
|
||||
<pre>$ java org.mozilla.javascript.tools.shell.Main
|
||||
js> importClass(Packages.org.mozilla.javascript.Context)
|
||||
js> cx = Context.enter()
|
||||
org.mozilla.javascript.Context@25980d62
|
||||
js> cx.evaluateString(this, "3+2", null, 0, null)
|
||||
5.0
|
||||
js> quit()
|
||||
$</pre>
|
||||
|
||||
<h2>
|
||||
Extending Java Classes and Implementing Java Interfaces with JavaScript</h2>
|
||||
Starting from the example above of creating a Java frame using JavaScript,
|
||||
we can add a listener for the button. Once we call <tt>addActionListener</tt>
|
||||
we can then click on the button to get the current date printed out:
|
||||
<pre>$ java org.mozilla.javascript.tools.shell.Main
|
||||
js> importPackage(java.awt);
|
||||
js> frame = new Frame("JavaScript")
|
||||
java.awt.Frame[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,resizable,title=JavaScript]
|
||||
js> button = new Button("OK")
|
||||
java.awt.Button[button0,0,0,0x0,invalid,label=OK]
|
||||
js> frame.setSize(new Dimension(200,100))
|
||||
js> frame.add(button)
|
||||
java.awt.Button[button0,0,0,0x0,invalid,label=OK]
|
||||
js> frame.show()
|
||||
js> function printDate() { print(new Date()) }
|
||||
js> printDate()
|
||||
Wed Mar 15 15:42:20 GMT-0800 (PST) 2000
|
||||
js> o = { actionPerformed: printDate }
|
||||
[object Object]
|
||||
js> o.actionPerformed()
|
||||
Wed Mar 15 15:42:39 GMT-0800 (PST) 2000
|
||||
js> buttonListener = java.awt.event.ActionListener(o)
|
||||
adapter0@6acc0f66
|
||||
js> button.addActionListener(buttonListener)
|
||||
js> Wed Mar 15 15:43:05 GMT-0800 (PST) 2000
|
||||
Wed Mar 15 15:43:05 GMT-0800 (PST) 2000
|
||||
Wed Mar 15 15:43:08 GMT-0800 (PST) 2000
|
||||
quit()
|
||||
$</pre>
|
||||
When we type <tt>buttonListener = java.awt.event.ActionListener(o)</tt>,
|
||||
Rhino actually creates a new Java class that implements <tt>ActionListener</tt>
|
||||
and forwards calls from that class to the JavaScript object. So when you
|
||||
click on the button, the <tt>printDate</tt> method is called.
|
||||
<p>
|
||||
Starting from the release 1.5R5 Rhino allows to pass JavaScript functions directly to Java methods if the corresponding argument is Java interface with single method. It allows to pass <tt>printDate</tt> directly to <tt>addActionListener</tt> and simplifies example:
|
||||
<pre>$ java org.mozilla.javascript.tools.shell.Main
|
||||
js> importPackage(java.awt);
|
||||
js> frame = new Frame("JavaScript")
|
||||
java.awt.Frame[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=JavaScript,resizable,normal]
|
||||
js> button = new Button("OK")
|
||||
java.awt.Button[button0,0,0,0x0,invalid,label=OK]
|
||||
js> frame.setSize(new Dimension(200,100))
|
||||
js> frame.add(button)
|
||||
java.awt.Button[button0,0,0,0x0,invalid,label=OK]
|
||||
js> frame.show()
|
||||
js> function printDate() { print(new Date()) }
|
||||
js> printDate()
|
||||
Mon Oct 27 2003 10:35:44 GMT+0100 (CET)
|
||||
js> button.addActionListener(printDate)
|
||||
js> Mon Oct 27 2003 10:36:09 GMT+0100 (CET)
|
||||
Mon Oct 27 2003 10:36:10 GMT+0100 (CET)
|
||||
quit()
|
||||
$</pre>
|
||||
|
||||
<h2>
|
||||
JavaAdapter constructor</h2>
|
||||
Another way to create a JavaAdapter is to call the JavaAdapter constructor
|
||||
explicitly. Using the JavaAdapter constructor gives you additional features
|
||||
that cannot be had by "constructing" a Java interface as was done above.
|
||||
<p>Instead of writing
|
||||
<pre> buttonListener = java.awt.event.ActionListener(o)</pre>
|
||||
above we can also write
|
||||
<pre> buttonListener = new JavaAdapter(java.awt.event.ActionListener, o)</pre>
|
||||
which is equivalent. If we also wanted to extend class <tt>Foo</tt>, while
|
||||
also implementing <tt>java.lang.Runnable</tt>, we would write
|
||||
<pre> buttonListener = new JavaAdapter(Packages.Foo,
|
||||
java.awt.event.ActionListener,
|
||||
java.lang.Runnable, o)</pre>
|
||||
In general the syntax is
|
||||
<p> <tt>new JavaAdapter(</tt><i>java-class</i>, [<i>java-class</i>,
|
||||
...] <i>javascript-object</i><tt>)</tt>
|
||||
<p>where at most one <i>java-class</i> is a Java class and the remaining
|
||||
<i>java-class</i>es
|
||||
are interfaces. The result will be a Java adapter that extends any specified
|
||||
Java class, implements the Java interfaces, and forwards any calls to the
|
||||
methods of the <i>javascript-object</i>.
|
||||
<h3>
|
||||
|
||||
<hr WIDTH="100%"><br>
|
||||
<a href="index.html">back to top</a></h3>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 4.0 KiB |
@@ -1,122 +0,0 @@
|
||||
<!DOCTYPE html PUBLIC "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
|
||||
<meta name="GENERATOR" content="Mozilla/4.72 [en]C-NSCP (WinNT; U) [Netscape]">
|
||||
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Serialization</title>
|
||||
</head>
|
||||
<body bgcolor="#ffffff">
|
||||
|
||||
<script src="owner.js"></script>
|
||||
<center>
|
||||
<h1>Serialization</h1>
|
||||
</center>
|
||||
|
||||
<script>document.write(owner());</script> <br>
|
||||
<script>
|
||||
var d = new Date(document.lastModified);
|
||||
document.write((d.getMonth()+1)+"/"+d.getDate()+"/"+d.getFullYear());
|
||||
document.write('<br>');
|
||||
</script>
|
||||
<center>
|
||||
<hr width="100%"></center>
|
||||
|
||||
<p>Beginning with Rhino 1.5 Release 3 it is possible to serialize JavaScript
|
||||
objects, including functions and scripts. However, serialization of
|
||||
code in compilation mode has some significant limitations.. Serialization
|
||||
provides a way to save the state of an object and write it out to a file
|
||||
or send it across a network connection. <br>
|
||||
</p>
|
||||
<h2>Simple serialization example</h2>
|
||||
The Rhino shell has two new top-level functions, serialize and deserialize.
|
||||
They're intended mainly as examples of the use of serialization:<br>
|
||||
<pre>$ java org.mozilla.javascript.tools.shell.Main<br>js> function f() { return 3; }<br>js> serialize(f, "f.ser")<br>js> quit()<br><br>$ java org.mozilla.javascript.tools.shell.Main<br>js> f = deserialize("f.ser")<br><br>function f() {<br> return 3;<br>}<br><br>js> f()<br>3<br>js></pre>
|
||||
<pre></pre>
|
||||
<pre></pre>
|
||||
<pre></pre>
|
||||
<pre></pre>
|
||||
<pre></pre>
|
||||
<pre></pre>
|
||||
<pre></pre>
|
||||
<pre></pre>
|
||||
<pre></pre>
|
||||
Here we see a simple case of a function being serialized to a file and then
|
||||
read into a new instance of Rhino and called. <br>
|
||||
<br>
|
||||
<h2>Rhino serialization APIs</h2>
|
||||
Two new classes, ScriptableOutputStream and ScriptableInputStream, were introduced
|
||||
to handle serialization of Rhino classes. These classes extend ObjectOutputStream
|
||||
and ObjectInputStream respectively. Writing an object to a file can be done
|
||||
in a few lines of Java code:<br>
|
||||
<pre>FileOutputStream fos = new FileOutputStream(filename);<br>ScriptableOutputStream out = new ScriptableOutputStream(fos, scope);<br>out.writeObject(obj);<br>out.close();</pre>
|
||||
<p>Here filename is the file to write to, obj is the object or function to
|
||||
write, and scope is the top-level scope containing obj. </p>
|
||||
<p>Reading the serialized object back into memory is similarly simple:</p>
|
||||
<pre>FileInputStream fis = new FileInputStream(filename);<br>ObjectInputStream in = new ScriptableInputStream(fis, scope);<br>Object deserialized = in.readObject();<br>in.close();<br></pre>
|
||||
<p>Again, we need the scope to create our serialization stream class. </p>
|
||||
<p>So why do we need these specialized stream classes instead of simply using
|
||||
ObjectOutputStream and ObjectInputStream? To understand the answer we must
|
||||
know what goes on behind the scenes when Rhino serializes objects. </p>
|
||||
<h2>How Rhino serialization works</h2>
|
||||
By default, Java serialization of an object also serializes objects that
|
||||
are referred to by that object. Upon deserialization the initial object and
|
||||
the objects it refers to are all created and the references between the objects
|
||||
are resolved. <br>
|
||||
<br>
|
||||
However, for JavaScript this creates a problem. JavaScript objects contain
|
||||
references to prototypes and to parent scopes. Default serialization would
|
||||
serialize the object or function we desired but would also serialize Object.prototype
|
||||
or even possibly the entire top-level scope and everything it refers to!
|
||||
We want to be able to serialize a JavaScript object and then deserialize
|
||||
it into a new scope and have all of the references from the deserialized
|
||||
object to prototypes and parent scopes resolved correctly to refer to objects
|
||||
in the new scope. <br>
|
||||
<br>
|
||||
ScriptableOutputStream takes a scope as a parameter to its constructor. If
|
||||
in the process of serialization it encounters a reference to the scope it
|
||||
will serialize a marker that will be resolved to the new scope upon deserialization.
|
||||
It is also possible to add names of objects to a list in the ScriptableOutputStream
|
||||
object. These objects will also be saved as markers upon serialization and
|
||||
resolved in the new scope upon deserialization. Use the addExcludedName method
|
||||
of ScriptableOutputStream to add new names. By default, ScriptableOutputStream
|
||||
excludes all the names defined using Context.initStandardObjects.<br>
|
||||
<br>
|
||||
If you are using Rhino serialization in an environment where you always define,
|
||||
say, a constructor "Foo", you should add the following code before calling
|
||||
writeObject:<br>
|
||||
<pre>out.addExcludedName("Foo");<br>out.addExcludedName("Foo.prototype");<br></pre>
|
||||
This code will prevent Foo and Foo.prototype from being serialized and will
|
||||
cause references to Foo or Foo.prototype to be resolved to the objects in
|
||||
the new scope upon deserialization. Exceptions will be thrown if Foo or Foo.prototype
|
||||
cannot be found the scopes used in either ScriptableOutputStream or ScriptableInputStream.<br>
|
||||
<br>
|
||||
<h2>Rhino serialization in compilation mode</h2>
|
||||
Serialization works well with objects and with functions and scripts in
|
||||
interpretive mode. However, you can run into problems with serialization
|
||||
of compiled functions and scripts:<br>
|
||||
<pre>$ cat test.js<br>function f() { return 3; }<br>serialize(f, "f.ser");<br>g = deserialize("f.ser");<br>print(g());<br>$ java org.mozilla.javascript.tools.shell.Main -opt -1 test.js<br>3<br>$ java org.mozilla.javascript.tools.shell.Main test.js<br>js: uncaught JavaScript exception: java.lang.ClassNotFoundException: c1<br></pre>
|
||||
<p>The problem is that Java serialization has no built-in way to serialize
|
||||
Java classes themselves. (It might be possible to save the Java bytecodes
|
||||
in an array and then load the class upon deserialization, but at best that
|
||||
would eat up a lot of memory for just this feature.) One way around this
|
||||
is to compile the functions using the jsc tool: </p>
|
||||
<pre>$ cat f.js<br>function f() { return 3; }<br>$ java -classpath js.jar org.mozilla.javascript.tools.jsc.Main f.js<br>$ cat test2.js<br>loadClass("f");<br>serialize(f, "f.ser");<br>g = deserialize("f.ser");<br>print(g());<br>$ java -classpath 'js.jar;.' org.mozilla.javascript.tools.shell.Main test2.js<br>3<br></pre>
|
||||
<p> Now the function f is compiled to a Java class, but that class is
|
||||
then made available in the classpath so serialization works. This isn't that
|
||||
interesting an example since compiling a function to a class and then loading
|
||||
it accomplishes the same as serializing an interpreted function, but it becomes
|
||||
more relevant if you wish to serialize JavaScript objects that have references
|
||||
to compiled functions. </p>
|
||||
<h3>
|
||||
<hr width="100%"><br>
|
||||
<a href="index.html">back to top</a>
|
||||
</h3>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,234 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.7 [en]C-NSCP (WinNT; U) [Netscape]">
|
||||
<title>JavaScript Shell</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
JavaScript Shell</h1></center>
|
||||
The JavaScript shell provides a simple way to run scripts in batch mode
|
||||
or an interactive environment for exploratory programming.
|
||||
<h2>
|
||||
Invoking the Shell</h2>
|
||||
<tt>java org.mozilla.javascript.tools.shell.Main [<i>options</i>]
|
||||
<i>script-filename-or-url</i> [<i>script-arguments</i>]</tt>
|
||||
<p>where <tt><i>options</i></tt> are:
|
||||
<p><tt>-e <i>script-source</i></tt>
|
||||
<blockquote>Executes <i>script-source</i> as a JavaScript script.</blockquote>
|
||||
<tt>-f <i>script-filename-or-url</i></tt>
|
||||
<blockquote>Reads <i>script-filename-or-url</i> content and execute it as a JavaScript script.</blockquote>
|
||||
<tt>-opt <i>optLevel</i></tt>
|
||||
<br><tt>-O <i>optLevel</i></tt>
|
||||
<ul>Optimizes at level <i>optLevel</i>, which must be an integer between
|
||||
0 and 9. See <a href="opt.html">Optimization</a> for more details.</ul>
|
||||
<tt>-version <i>versionNumber</i></tt>
|
||||
<ul>Specifies the language version to compile with. The string <i>versionNumber</i>
|
||||
must be one of <tt>100</tt>, <tt>110</tt>, <tt>120</tt>, <tt>130</tt>,
|
||||
or <tt>140</tt>. See <a href="overview.html#versions">JavaScript Language
|
||||
Versions</a> for more information on language versions.</ul>
|
||||
|
||||
If the shell is invoked with the system property rhino.use_java_policy_security set to true and with a security manager installed, the shell restricts scripts permissions based on their URLs according to Java policy settings. This is available only if JVM implements Java2 security model.
|
||||
<h2>
|
||||
Predefined Properties</h2>
|
||||
Scripts executing in the shell have access to some additional properties
|
||||
of the top-level object.
|
||||
<br>
|
||||
<h4>
|
||||
arguments</h4>
|
||||
|
||||
<blockquote>The <tt>arguments</tt> object is an array containing the strings
|
||||
of all the arguments given at the command line when the shell was invoked.</blockquote>
|
||||
|
||||
<h4>
|
||||
help()</h4>
|
||||
|
||||
<blockquote>Executing the help function will print usage and help messages.</blockquote>
|
||||
|
||||
<h4>
|
||||
defineClass(<i>className</i>)</h4>
|
||||
|
||||
<blockquote>Define an extension using the Java class named with the string
|
||||
argument <i>className</i>. Uses ScriptableObject.defineClass() to define
|
||||
the extension.</blockquote>
|
||||
|
||||
<h4>
|
||||
deserialize(<i>filename</i>)</h4>
|
||||
|
||||
<blockquote>Restore from the specified file an object previously written by a call to <tt>serialize</tt>.</blockquote>
|
||||
|
||||
<h4>
|
||||
load([<i>filename</i>, ...])</h4>
|
||||
|
||||
<blockquote>Load JavaScript source files named by string arguments. If
|
||||
multiple arguments are given, each file is read in and executed in turn.</blockquote>
|
||||
|
||||
<h4>
|
||||
loadClass(<i>className</i>)</h4>
|
||||
|
||||
<blockquote>Load and execute the class named by the string argument <i>className</i>.
|
||||
The class must be a class that implements the Script interface, as will
|
||||
any script compiled by <a href="jsc.html">jsc</a>.</blockquote>
|
||||
|
||||
<h4>
|
||||
print([<i>expr</i> ...])</h4>
|
||||
|
||||
<blockquote>Evaluate and print expressions. Evaluates each expression,
|
||||
converts the result to a string, and prints it.</blockquote>
|
||||
|
||||
<h4>
|
||||
readFile(<i>path</i> [, <i>characterCoding</i>)</h4>
|
||||
|
||||
<blockquote>Read given file and convert its bytes to a string using the
|
||||
specified character coding or default character coding if explicit coding
|
||||
argument is not given.</blockquote>
|
||||
|
||||
<h4>
|
||||
readUrl(<i>url</i> [, <i>characterCoding</i>)</h4>
|
||||
|
||||
<blockquote>Open an input connection to the given string url, read all its
|
||||
bytes and convert them to a string using the specified character coding or
|
||||
default character coding if explicit coding argument is not given.</blockquote>
|
||||
|
||||
<h4>
|
||||
runCommand(<i>commandName</i>, [<i>arg</i>, ...] [<i>options</i>])</h4>
|
||||
|
||||
<blockquote>Execute the specified command with the given argument and options
|
||||
as a separate process and return the exit status of the process. For details, see JavaDoc for <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/toolsrc/org/mozilla/javascript/tools/shell/Global.java">org.mozilla.javascript.tools.shell.Global#runCommand</a>.</blockquote>
|
||||
|
||||
<h4>
|
||||
serialize(<i>object</i>, <i>filename</i>)</h4>
|
||||
<blockquote>Serialize the given object to the specified file.</blockquote>
|
||||
|
||||
<h4>
|
||||
spawn(<i>functionOrScript</i>)</h4>
|
||||
|
||||
<blockquote>Run the given function or script in a different thread.</blockquote>
|
||||
|
||||
<h4>
|
||||
sync(<i>function</i>)</h4>
|
||||
|
||||
<blockquote>creates a synchronized function (in the sense of a Java synchronized method) from an existing function. The new function synchronizes on the <code>this</code> object of its invocation.</blockquote>
|
||||
|
||||
<h4>
|
||||
quit()</h4>
|
||||
|
||||
<blockquote>Quit shell. The shell will also quit in interactive mode if
|
||||
an end-of-file character is typed at the prompt.</blockquote>
|
||||
|
||||
<h4>
|
||||
version([<i>number</i>])</h4>
|
||||
|
||||
<blockquote>Get or set JavaScript version number. If no argument is supplied,
|
||||
the current version number is returned. If an argument is supplied, it
|
||||
is expected to be one of <tt>100</tt>, <tt>110</tt>, <tt>120</tt>, <tt>130,</tt>
|
||||
or <tt>140</tt> to indicate JavaScript version 1.0, 1.1, 1.2, 1.3, or 1.4
|
||||
respectively.</blockquote>
|
||||
|
||||
<h2>
|
||||
Example</h2>
|
||||
|
||||
<h4>Invocation</h4>
|
||||
Here the shell is invoked three times from the command line. (The system
|
||||
command prompt is shown as <tt>$</tt>.) The first invocation executes a
|
||||
script specified on the command line itself. The next invocation has no
|
||||
arguments, so the shell goes into interactive mode, reading and evaluating
|
||||
each line as it is typed in. Finally, the last invocation executes a script
|
||||
from a file and accesses arguments to the script itself.
|
||||
<pre>
|
||||
$ java org.mozilla.javascript.tools.shell.Main -e print('hi')
|
||||
hi
|
||||
$ java org.mozilla.javascript.tools.shell.Main
|
||||
js> print('hi')
|
||||
hi
|
||||
js> 6*7
|
||||
42
|
||||
js> function f() {
|
||||
return a;
|
||||
}
|
||||
js> var a = 34;
|
||||
js> f()
|
||||
34
|
||||
js> quit()
|
||||
$ cat echo.js
|
||||
for (i in arguments) {
|
||||
print(arguments[i])
|
||||
}
|
||||
$ java org.mozilla.javascript.tools.shell.Main echo.js foo bar
|
||||
foo
|
||||
bar
|
||||
$
|
||||
</pre>
|
||||
|
||||
<h4>spawn and sync</h4>
|
||||
The following example creates 2 threads via <tt>spawn</tt> and uses <tt>sync</tt> to create a synchronized version of the function <tt>test</tt>.
|
||||
|
||||
<pre>
|
||||
js> function test(x) {
|
||||
print("entry");
|
||||
java.lang.Thread.sleep(x*1000);
|
||||
print("exit");
|
||||
}
|
||||
js> var o = { f : sync(test) };
|
||||
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
|
||||
</pre>
|
||||
|
||||
<h4>runCommand</h4>
|
||||
Here is few examples of invoking <tt>runCommand</tt> under Linux.
|
||||
<pre>
|
||||
js> runCommand('date')
|
||||
Thu Jan 23 16:49:36 CET 2003
|
||||
0
|
||||
// Using input option to provide process input
|
||||
js> runCommand("sort", {input: "c\na\nb"})
|
||||
a
|
||||
b
|
||||
c
|
||||
0
|
||||
js> // Demo of output and err options
|
||||
js> var opt={input: "c\na\nb", output: 'Sort Output:\n'}
|
||||
js> runCommand("sort", opt)
|
||||
0
|
||||
js> print(opt.output)
|
||||
Sort Output:
|
||||
a
|
||||
b
|
||||
c
|
||||
js> var opt={input: "c\na\nb", output: 'Sort Output:\n', err: ''}
|
||||
js> runCommand("sort", "--bad-arg", opt)
|
||||
2
|
||||
js> print(opt.err)
|
||||
/bin/sort: unrecognized option `--bad-arg'
|
||||
Try `/bin/sort --help' for more information.
|
||||
|
||||
js> runCommand("bad_command", "--bad-arg", opt)
|
||||
js: "<stdin>", line 18: uncaught JavaScript exception: java.io.IOException: bad_command: not found
|
||||
js> // Passing explicit environment to the system shell
|
||||
js> runCommand("sh", "-c", "echo $env1 $env2", { env: {env1: 100, env2: 200}})
|
||||
100 200
|
||||
0
|
||||
js> // Use args option to provide additional command arguments
|
||||
js> var arg_array = [1, 2, 3, 4];
|
||||
js> runCommand("echo", { args: arg_array})
|
||||
1 2 3 4
|
||||
0
|
||||
</pre>
|
||||
|
||||
|
||||
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="index.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,31 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.7 [en]C-NSCP (WinNT; U) [Netscape]">
|
||||
<title>JavaScript Tools</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
JavaScript Tools</h1></center>
|
||||
|
||||
<h2>
|
||||
JavaScript shell</h2>
|
||||
The <a href="shell.html">JavaScript shell</a> allows for interactive and
|
||||
batch execution of JavaScript scripts.
|
||||
<br>
|
||||
<br>
|
||||
<br>
|
||||
<h2>
|
||||
JavaScript compiler</h2>
|
||||
The <a href="jsc.html">JavaScript compiler</a> translates JavaScript source
|
||||
into Java class files.
|
||||
<br>
|
||||
<p>
|
||||
<hr WIDTH="100%">
|
||||
<br><a href="index.html">back to top</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,357 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Generator" content="Microsoft Word 97">
|
||||
<meta name="GENERATOR" content="Mozilla/4.75 [en] (WinNT; U) [Netscape]">
|
||||
<title>Embedding Rhino</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<center><font size=+4>Tutorial: Embedding Rhino</font></center>
|
||||
|
||||
<p>Embedding Rhino can be done simply with good results. With more effort
|
||||
on the part of the embedder, the objects exposed to scripts can be customized
|
||||
further.
|
||||
<p>This tutorial leads you through the steps from a simple embedding to
|
||||
more customized, complex embeddings. Fully compilable examples are provided
|
||||
along the way.
|
||||
<p>The examples live in the <tt>rhino/examples</tt> directory in the distribution
|
||||
and in <tt>mozilla/js/rhino/examples</tt> in cvs. This document will link
|
||||
to them using <a href="http://lxr.mozilla.org/">lxr</a>.
|
||||
<p>In this document, JavaScript code will be in <font color="#006600">green</font>,
|
||||
Java code will be in <font color="#006600">green</font>, and shell logs
|
||||
will be in <font color="#663366">purple</font>.
|
||||
<h3>
|
||||
<font size=+3>Contents</font></h3>
|
||||
|
||||
<ul>
|
||||
<li>
|
||||
<font size=+1><a href="#RunScript">RunScript: A simple embedding</a></font></li>
|
||||
|
||||
<ul>
|
||||
<li>
|
||||
<font size=+1><a href="#EnteringContext">Entering a Context</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#initializing">Initializing standard objects</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#Collecting">Collecting the arguments</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#Evaluating">Evaluating a script</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#Print">Print the result</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#Exit">Exit the Context</a></font></li>
|
||||
</ul>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#Expose">Expose Java APIs</a></font></li>
|
||||
|
||||
<ul>
|
||||
<li>
|
||||
<font size=+1><a href="#UseJava">Use Java APIs</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#ImplementingInterfaces">Implementing interfaces</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#AddJava">Add Java objects</a></font></li>
|
||||
</ul>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#UsingJSObjs">Using JavaScript objects from Java</a></font></li>
|
||||
|
||||
<ul>
|
||||
<li>
|
||||
<font size=+1><a href="#UsingJSvars">Using JavaScript variables</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#CallingJSfuns">Calling JavaScript functions</a></font></li>
|
||||
</ul>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#JavaScriptHostObjects">JavaScript host objects</a></font></li>
|
||||
|
||||
<ul>
|
||||
<li>
|
||||
<font size=+1><a href="#DefiningHostObjects">Defining Host Objects</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#Counter">Counter example</a></font></li>
|
||||
|
||||
<ul>
|
||||
<li>
|
||||
<font size=+1><a href="#CounterCtors">Counter's constructors</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#classname">Class name</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#Dynamic">Dynamic properties</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#DefiningMethods">Defining JavaScript "methods"</a></font></li>
|
||||
|
||||
<li>
|
||||
<font size=+1><a href="#AddingCounter">Adding Counter to RunScript</a></font></li>
|
||||
</ul>
|
||||
</ul>
|
||||
</ul>
|
||||
|
||||
<hr WIDTH="100%">
|
||||
<br><a NAME="RunScript"></a><font size=+3>RunScript: A simple embedding</font>
|
||||
<p>About the simplest embedding of Rhino possible is the <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/RunScript.java">RunScript
|
||||
example</a>. All it does it read a script from the command line, execute
|
||||
it, and print a result.
|
||||
<p>Here's an example use of RunScript from a shell command line:
|
||||
<blockquote>
|
||||
<pre><font color="#663366">$ java RunScript "Math.cos(Math.PI)"
|
||||
-1
|
||||
$ java RunScript 'function f(x){return x+1} f(7)'
|
||||
8</font></pre>
|
||||
</blockquote>
|
||||
Note that you'll have to have both the Rhino classes and the RunScript
|
||||
example class file in the classpath. Let's step through the body of <tt>main</tt>
|
||||
one line at time.
|
||||
<p><a NAME="EnteringContext"></a><font size=+2>Entering a Context</font>
|
||||
<p>The code
|
||||
<blockquote>
|
||||
<pre><font color="#006600">Context cx = Context.enter();</font></pre>
|
||||
</blockquote>
|
||||
Creates and enters a <tt>Context. </tt>A <tt>Context</tt> stores information
|
||||
about the execution environment of a script.
|
||||
<br>
|
||||
<p><a NAME="initializing"></a><font size=+2>Initializing standard objects</font>
|
||||
<p>The code
|
||||
<blockquote>
|
||||
<pre><font color="#006600">Scriptable scope = cx.initStandardObjects();</font></pre>
|
||||
</blockquote>
|
||||
Initializes the standard objects (<tt>Object</tt>,
|
||||
<tt>Function</tt>, etc.)
|
||||
This must be done before scripts can be executed. The <tt>null</tt> parameter
|
||||
tells <tt>initStandardObjects</tt> to create and return a scope object
|
||||
that we use in later calls.
|
||||
<p><a NAME="Collecting"></a><font size=+2>Collecting the arguments</font>
|
||||
<p>This code is standard Java and not specific to Rhino. It just collects
|
||||
all the arguments and concatenates them together.
|
||||
<blockquote>
|
||||
<pre style="color: #006600">
|
||||
String s = "";
|
||||
for (int i=0; i < args.length; i++) {
|
||||
s += args[i];
|
||||
}
|
||||
</pre>
|
||||
</blockquote>
|
||||
<p><br><a NAME="Evaluating"></a><font size=+2>Evaluating a script</font>
|
||||
<p>The code
|
||||
<blockquote>
|
||||
<pre><font color="#006600">Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);</font></pre>
|
||||
</blockquote>
|
||||
uses the Context <tt>cx</tt> to evaluate a string. Evaluation of the script
|
||||
looks up variables in <tt>scope</tt>, and errors will be reported with
|
||||
the filename <tt><cmd></tt> and line number 1.
|
||||
<br>
|
||||
<p><a NAME="Print"></a><font size=+2>Print the result</font>
|
||||
<p>The code
|
||||
<blockquote>
|
||||
<pre><font color="#006600">System.out.println(cx.toString(result));</font></pre>
|
||||
</blockquote>
|
||||
prints the result of evaluating the script (contained in the variable <tt>result</tt>).
|
||||
<tt>result</tt>
|
||||
could be a string, JavaScript object, or other values..The
|
||||
<tt>toString</tt>
|
||||
method converts any JavaScript value to a string.
|
||||
<br>
|
||||
<p><a NAME="Exit"></a><font size=+2>Exit the Context</font>
|
||||
<p>The code
|
||||
<blockquote>
|
||||
<pre style="color: #006600">
|
||||
} finally {
|
||||
Context.exit();
|
||||
}
|
||||
</pre>
|
||||
</blockquote>
|
||||
exits the Context. This removes the association between the Context and
|
||||
the current thread and is an essential cleanup action. There should be
|
||||
a call to <tt>exit</tt> for every call to <tt>enter</tt>. To make sure that it is called even if an exception is thrown, it is put into the finally block corresponding to the try block starting after <tt>Context.enter()</tt>.
|
||||
<br>
|
||||
<dir> </dir>
|
||||
<a NAME="Expose"></a><font size=+3>Expose Java APIs</font>
|
||||
<p><a NAME="UseJava"></a><font size=+2>Use Java APIs</font>
|
||||
<p>No additional code in the embedding needed! The JavaScript feature called
|
||||
<i>LiveConnect</i>
|
||||
allows JavaScript programs to interact with Java objects:
|
||||
<dir><tt><font color="#663366">$ java RunScript 'java.lang.System.out.println(3)'</font></tt>
|
||||
<br><tt><font color="#663366">3.0</font></tt>
|
||||
<br><tt><font color="#663366">undefined</font></tt></dir>
|
||||
<a NAME="ImplementingInterfaces"></a><font size=+2>Implementing interfaces</font>
|
||||
<p>Using Rhino, JavaScript objects can implement arbitrary Java interfaces.
|
||||
There's no Java code to write--it's part of Rhino's LiveConnect implementation.
|
||||
For example, we can see how to implement java.lang.Runnable in a Rhino
|
||||
shell session:
|
||||
<blockquote>
|
||||
<pre><font color="#663366">js> obj = { run: function() { print('hi'); } }
|
||||
[object Object]
|
||||
js> obj.run()
|
||||
hi
|
||||
js> r = new java.lang.Runnable(obj);
|
||||
[object Object]
|
||||
js> t = new java.lang.Thread(r)
|
||||
Thread[Thread-0,5,main]
|
||||
js> t.start()
|
||||
hi</font></pre>
|
||||
</blockquote>
|
||||
<a NAME="AddJava"></a><font size=+2>Add Java objects</font>
|
||||
<p>The next example is <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/RunScript2.java">RunScript2</a>.
|
||||
This is the same as RunScript, but with the addition of two extra lines
|
||||
of code:
|
||||
<dir><tt><font color="#006600">Scriptable jsArgs = Context.toObject(System.out,
|
||||
scope);</font></tt>
|
||||
<br><tt><font color="#006600">scope.put("out", scope, jsArgs);</font></tt></dir>
|
||||
These lines add a global variable <tt>out</tt> that is a JavaScript reflection
|
||||
of the <tt>System.out</tt> variable:
|
||||
<dir><tt><font color="#663366">$ java RunScript2 'out.println(42)'</font></tt>
|
||||
<br><tt><font color="#663366">42.0</font></tt>
|
||||
<br><tt><font color="#663366">undefined</font></tt></dir>
|
||||
|
||||
<p><br><a NAME="UsingJSObjs"></a><font size=+3>Using JavaScript objects
|
||||
from Java</font>
|
||||
<p>After evaluating a script it's possible to query the scope for variables
|
||||
and functions, extracting values and calling JavaScript functions. This
|
||||
is illustrated in the <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/RunScript3.java">RunScript3</a>
|
||||
example. This example adds the ability to print the value of variable <tt>x</tt>
|
||||
and the result of calling function <tt>f</tt>. Both <tt>x</tt> and <tt>f</tt>
|
||||
are expected to be defined by the evaluated script. For example,
|
||||
<blockquote>
|
||||
<pre style="color: #663366">
|
||||
$ java RunScript3 'x = 7'
|
||||
x = 7
|
||||
f is undefined or not a function.
|
||||
$ java RunScript3 'function f(a) { return a; }'
|
||||
x is not defined.
|
||||
f('my args') = my arg
|
||||
</pre>
|
||||
</blockquote>
|
||||
<a NAME="UsingJSvars"></a><font size=+2>Using JavaScript variables</font>
|
||||
<p>To print out the value of <tt>x</tt>, we add the following code.
|
||||
<blockquote>
|
||||
<pre style="color: #006600">
|
||||
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));
|
||||
}
|
||||
</pre>
|
||||
</blockquote>
|
||||
<a NAME="CallingJSfuns"></a><font size=+2>Calling JavaScript functions</font>
|
||||
<p>To get the function <tt>f</tt>, call it, and print the result, we add
|
||||
this code:
|
||||
<blockquote>
|
||||
<pre style="color: #006600">
|
||||
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);
|
||||
}
|
||||
</pre>
|
||||
</blockquote>
|
||||
<p><br><a NAME="JavaScriptHostObjects"></a><font size=+3>JavaScript host
|
||||
objects</font>
|
||||
<p><a NAME="DefiningHostObjects"></a><font size=+2>Defining Host Objects</font>
|
||||
<p>Custom host objects can implement special JavaScript features like dynamic
|
||||
properties.
|
||||
<p><a NAME="Counter"></a><font size=+2>Counter example</font>
|
||||
<p>The <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/Counter.java">Counter
|
||||
example</a> is a simple host object. We'll go through it method by method
|
||||
below.
|
||||
<p>It's easy to try out new host object classes in the shell using its
|
||||
built-in <tt>defineClass</tt> function. We'll see how to add it to RunScript
|
||||
later. (Note that because the <tt>java -jar</tt> option preempts the rest
|
||||
of the classpath, we can't use that and access the <tt>Counter</tt> class.)
|
||||
<blockquote>
|
||||
<pre style="color: #663366">
|
||||
$ java -cp 'js.jar;examples' org.mozilla.javascript.tools.shell.Main
|
||||
js> 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
|
||||
0
|
||||
</pre>
|
||||
</blockquote>
|
||||
<a NAME="CounterCtors"></a><font size=+2>Counter's constructors</font>
|
||||
<p>The zero-argument constructor is used by Rhino runtime to create instances.
|
||||
For the counter example, no initialization work is needed, so the implementation
|
||||
is empty.
|
||||
<dir><tt><font color="#006600">public Counter () { }</font></tt></dir>
|
||||
The method <tt>jsConstructor</tt> defines the JavaScript constructor that
|
||||
was called with the expression <tt>new Counter(7)</tt> in the JavaScript
|
||||
code above.
|
||||
<dir><tt><font color="#006600">public void jsConstructor(int a) { count
|
||||
= a; }</font></tt></dir>
|
||||
<a NAME="classname"></a><font size=+2>Class name</font>
|
||||
<p>The class name is defined by the <tt>getClassName</tt> method. This
|
||||
is used to determine the name of the constructor.
|
||||
<dir><tt><font color="#006600">public String getClassName() { return "Counter";
|
||||
}</font></tt></dir>
|
||||
<a NAME="Dynamic"></a><font size=+2>Dynamic properties</font>
|
||||
<p>Dynamic properties are defined by methods beginning with <tt>jsGet_</tt>
|
||||
or <tt>jsSet_</tt>. The method <tt>jsGet_count</tt> defines the <i>count</i>
|
||||
property.
|
||||
<dir><tt><font color="#006600">public int jsGet_count() { return count++;
|
||||
}</font></tt></dir>
|
||||
The expression <tt>c.count</tt> in the JavaScript code above results in
|
||||
a call to this method.
|
||||
<p><a NAME="DefiningMethods"></a><font size=+2>Defining JavaScript "methods"</font>
|
||||
<p>Methods can be defined using the <tt>jsFunction_ prefix</tt>. Here we
|
||||
define <tt>resetCount</tt> for JavaScript.
|
||||
<dir><tt><font color="#006600">public void jsFunction_resetCount() { count
|
||||
= 0; }</font></tt></dir>
|
||||
The call <tt>c.resetCount()</tt> above calls this method.
|
||||
<p><a NAME="AddingCounter"></a><font size=+2>Adding Counter to RunScript</font>
|
||||
<p>Now take a look at the <a href="http://lxr.mozilla.org/mozilla/source/js/rhino/examples/RunScript4.java">RunScript4
|
||||
example</a>. It's the same as RunScript except for two additions. The method
|
||||
<tt>ScriptableObject.defineClass</tt>
|
||||
uses a Java class to define the Counter "class" in the top-level scope:
|
||||
<dir><tt><font color="#006600">ScriptableObject.defineClass(scope, Counter.class);</font></tt></dir>
|
||||
Now we can reference the <tt>Counter</tt> object from our script:
|
||||
<dir><tt><font color="#663366">$ java RunScript4 'c = new Counter(3); c.count;
|
||||
c.count;'</font></tt>
|
||||
<br><tt><font color="#663366">4</font></tt></dir>
|
||||
It also creates a new instance of the <tt>Counter</tt> object from within
|
||||
our Java code, constructing it with the value 7, and assigning it to the
|
||||
top-level variable <tt>myCounter</tt>:
|
||||
<blockquote>
|
||||
<pre style="color: #006600">
|
||||
Object[] arg = { new Integer(7) };
|
||||
Scriptable myCounter = cx.newObject(scope, "Counter", arg);
|
||||
scope.put("myCounter", scope, myCounter);
|
||||
</pre>
|
||||
</blockquote>
|
||||
Now we can reference the <tt>myCounter</tt> object from our script:
|
||||
<blockquote>
|
||||
<pre style="color: #663366">
|
||||
$ java RunScript3 'RunScript4 'myCounter.count; myCounter.count'
|
||||
8
|
||||
</pre>
|
||||
</blockquote>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,77 +0,0 @@
|
||||
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
||||
<meta name="Author" content="Norris Boyd">
|
||||
<meta name="GENERATOR" content="Mozilla/4.72 [en]C-NSCP (WinNT; U) [Netscape]">
|
||||
<meta name="KeyWords" content="Rhino, JavaScript, Java">
|
||||
<title>Using Rhino</title>
|
||||
</head>
|
||||
<body bgcolor="#FFFFFF">
|
||||
<script src="owner.js"></script>
|
||||
|
||||
<center>
|
||||
<h1>
|
||||
How are people using Rhino?</h1></center>
|
||||
Here's a partial list of the ways people are using Rhino in their projects.
|
||||
The initial list was collected by Netscape marketing, so Rhino is referred
|
||||
to as Netscape Java-based JavaScript. We'd love to hear how you're using
|
||||
Rhino--just mail <script>document.write(owner());</script>
|
||||
.
|
||||
<p><a href="http://www.attachmate.com">Attachmate</a>
|
||||
<br>"Netscape JavaScript 1.5 with Java implementation was a perfect solution
|
||||
for developing our MacroRecorder because it made our development process
|
||||
faster and better, and our customers get a more efficient, reliable, and
|
||||
standards based product as a result," said Rob Clark, Director of Product
|
||||
Development at Attachmate. Attachmate integrates Netscape's Java-based
|
||||
JavaScript 1.5 Interpreter into its 100% Pure Java certified web-to-host
|
||||
thin clients, called e-Vantage Viewers. The Netscape Java-based JavaScript
|
||||
interpreter is used in a MacroRecorder feature that allows browser-based
|
||||
users to efficiently navigate host applications on mainframe and midrange
|
||||
systems.
|
||||
<p><a href="http://www.bristowhill.com/">Bristow Hill Software</a>
|
||||
<br>"We thought it would require lots of work to add scripting capability
|
||||
to Bristow Hill Server Pages, but we were delighted to find that Netscape
|
||||
JavaScript 1.5 with Java implementation fit right in with only a couple
|
||||
of lines of initialization code and one line of code to export our standard
|
||||
objects by name. Also, we were pleased to find we could take embedded scripting
|
||||
and compile it down to Java classes which could be used directly for greater
|
||||
speed in production. Netscape's JavaScript engine is rock solid and standards
|
||||
compliant, and my only regret is that we didn't start using it sooner,"
|
||||
said Don Anderson, President of Bristow Hill Software.
|
||||
<p><a href="http://www.icesoft.com/">ICEsoft Technologies</a>
|
||||
<br>ICEsoft Technologies adds JavaScript support to their <a href="http://www.icesoft.com/ps_browser_overview.html">ICEbrowser</a> using Rhino.
|
||||
<p><a href="http://homepage.mac.com/pcbeard/JShell/">JShell</a>
|
||||
<br>Rhino is used as the scripting language for the open source command
|
||||
shell JShell written by Patrick Beard.
|
||||
<p><a href="http://www.softcom.com">Softcom</a>
|
||||
<br>The tight integration of Netscape's Java-based JavaScript 1.5 with
|
||||
Softcom's Java-based RealPlayer plugin, RJ, enables Softcom to quickly
|
||||
produce dynamic interactive video applications for our media/entertainment,
|
||||
retail and professional education clients, helping us to synchronize the
|
||||
full interactivity of the Web and e-commerce with streaming video, said
|
||||
Chris O'Brien, president and COO of Softcom. For the enhanced Oscarcast
|
||||
recently produced for E! Online during the Academy Awards, Softcom used
|
||||
RJ to embed Netscape's JavaScript 1.5 in the RealPlayer, successfully integrating
|
||||
interactive chat and Java games, along with streaming video, within the
|
||||
RealPlayer.
|
||||
<p><a href="http://www.tdiinc.com/">Technology Deployment International</a>
|
||||
<br>"Technology Deployment International selected the Java-based Netscape
|
||||
JavaScript engine to incorporate into the workflow module of our eBusiness
|
||||
Management System (eBMS) allowing our customers to integrate business logic
|
||||
into any workstep of their application," said Dr. Kelvin Liu, VP eBMS Development,
|
||||
Technology Deployment International. "It has been easy to embed, the support
|
||||
we received from the engineering team has been outstanding, and the performance
|
||||
of the JavaScript code is almost identical to the equivalent Java."
|
||||
<p><a href="http://www.xypoint.com/">XYPOINT</a>
|
||||
<br>XYPOINT uses Rhino for automating test cases of their Java classes
|
||||
used in their service <a href="http://www.webwirelessnow.com/">WebWirelessNow</a>.
|
||||
Abraham Backus says that he's happy with Rhino because "I've always wanted
|
||||
this kind of JavaScript support."
|
||||
<h3>
|
||||
|
||||
<hr WIDTH="100%"><br>
|
||||
<a href="index.html">back to top</a></h3>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,105 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
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();
|
||||
|
||||
// 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 = null;
|
||||
try {
|
||||
result = cx.evaluateString(scope, "obj = {a:1, b:['x','y']}",
|
||||
"MySource", 1, null);
|
||||
}
|
||||
catch (JavaScriptException jse) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
try {
|
||||
// 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]));
|
||||
} catch (JavaScriptException e) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
cx.exit();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Norris Boyd
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
import org.mozilla.javascript.*;
|
||||
|
||||
public class Counter extends ScriptableObject {
|
||||
// The zero-argument constructor used by Rhino runtime to create instances
|
||||
public Counter() { }
|
||||
|
||||
// Method jsConstructor defines the JavaScript constructor
|
||||
public void jsConstructor(int a) { count = a; }
|
||||
|
||||
// The class name is defined by the getClassName method
|
||||
public String getClassName() { return "Counter"; }
|
||||
|
||||
// The method jsGet_count defines the count property.
|
||||
public int jsGet_count() { return count++; }
|
||||
|
||||
// Methods can be defined using the jsFunction_ prefix. Here we define
|
||||
// resetCount for JavaScript.
|
||||
public void jsFunction_resetCount() { count = 0; }
|
||||
|
||||
private int count;
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Norris Boyd
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
import org.mozilla.javascript.*;
|
||||
|
||||
/**
|
||||
* An example illustrating how to create a JavaScript object and retrieve
|
||||
* properties and call methods.
|
||||
* <p>
|
||||
* Output should be:
|
||||
* <pre>
|
||||
* count = 0
|
||||
* count = 1
|
||||
* resetCount
|
||||
* count = 0
|
||||
* </pre>
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Norris Boyd
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
import org.mozilla.javascript.*;
|
||||
|
||||
/**
|
||||
* Example of controlling the JavaScript with multiple scopes and threads.
|
||||
*/
|
||||
public class DynamicScopes {
|
||||
|
||||
/**
|
||||
* Main entry point.
|
||||
*
|
||||
* Set up the shared scope and then spawn new threads that execute
|
||||
* relative to that shared scope. Try compiling functions with and
|
||||
* without dynamic scope to see the effect.
|
||||
*
|
||||
* The expected output is
|
||||
* <pre>
|
||||
* sharedScope
|
||||
* sharedScope
|
||||
* sharedScope
|
||||
* thread0
|
||||
* thread1
|
||||
* thread2
|
||||
* </pre>
|
||||
* The final three lines may be permuted in any order depending on
|
||||
* thread scheduling.
|
||||
*/
|
||||
public static void main(String[] args)
|
||||
throws JavaScriptException
|
||||
{
|
||||
Context cx = Context.enter();
|
||||
try {
|
||||
cx.setCompileFunctionsWithDynamicScope(false);
|
||||
runScripts(cx);
|
||||
cx.setCompileFunctionsWithDynamicScope(true);
|
||||
runScripts(cx);
|
||||
} finally {
|
||||
cx.exit();
|
||||
}
|
||||
}
|
||||
|
||||
static void runScripts(Context cx)
|
||||
throws JavaScriptException
|
||||
{
|
||||
// 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 scope = cx.initStandardObjects(null, true);
|
||||
|
||||
// Now we can evaluate a script and functions will be compiled to
|
||||
// use dynamic scope if the Context is so initialized.
|
||||
String source = "var x = 'sharedScope';" +
|
||||
"function f() { return x; }";
|
||||
cx.evaluateString(scope, source, "MySource", 1, null);
|
||||
|
||||
// Now we spawn some threads that execute a script that calls the
|
||||
// function 'f'. The scope chain looks like this:
|
||||
// <pre>
|
||||
// ------------------
|
||||
// | shared scope |
|
||||
// ------------------
|
||||
// ^
|
||||
// |
|
||||
// ------------------
|
||||
// | per-thread scope |
|
||||
// ------------------
|
||||
// ^
|
||||
// |
|
||||
// ------------------
|
||||
// | f's activation |
|
||||
// ------------------
|
||||
// </pre>
|
||||
// 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 script = "function g() { var x = 'local'; return f(); }" +
|
||||
"java.lang.System.out.println(g());";
|
||||
t[i] = new Thread(new PerThread(scope, script,
|
||||
"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 scope, String script, String x) {
|
||||
this.scope = scope;
|
||||
this.script = script;
|
||||
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(scope);
|
||||
threadScope.setPrototype(scope);
|
||||
|
||||
// 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, script, "threadScript", 1, null);
|
||||
}
|
||||
catch (JavaScriptException jse) {
|
||||
// ignore
|
||||
}
|
||||
finally {
|
||||
Context.exit();
|
||||
}
|
||||
}
|
||||
private Scriptable scope;
|
||||
private String script;
|
||||
private String x;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,347 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Norris Boyd
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
import org.mozilla.javascript.*;
|
||||
import java.io.*;
|
||||
import java.util.Vector;
|
||||
|
||||
/**
|
||||
* Define a simple JavaScript File object.
|
||||
*
|
||||
* This isn't intended to be any sort of definitive attempt at a
|
||||
* standard File object for JavaScript, but instead is an example
|
||||
* of a more involved definition of a host object.
|
||||
*
|
||||
* Example of use of the File object:
|
||||
* <pre>
|
||||
* js> defineClass("File")
|
||||
* js> file = new File("myfile.txt");
|
||||
* [object File]
|
||||
* js> file.writeLine("one"); <i>only now is file actually opened</i>
|
||||
* js> file.writeLine("two");
|
||||
* js> file.writeLine("thr", "ee");
|
||||
* js> file.close(); <i>must close file before we can reopen for reading</i>
|
||||
* js> var a = file.readLines(); <i>creates and fills an array with the contents of the file</i>
|
||||
* js> a;
|
||||
* one,two,three
|
||||
* js>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
* File errors or end-of-file signaled by thrown Java exceptions will
|
||||
* be wrapped as JavaScript exceptions when called from JavaScript,
|
||||
* and may be caught within JavaScript.
|
||||
*
|
||||
* @author Norris Boyd
|
||||
*/
|
||||
public class File extends ScriptableObject {
|
||||
|
||||
/**
|
||||
* The zero-parameter constructor.
|
||||
*
|
||||
* When Context.defineClass is called with this class, it will
|
||||
* construct File.prototype using this constructor.
|
||||
*/
|
||||
public File() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The Java method defining the JavaScript File constructor.
|
||||
*
|
||||
* If the constructor has one or more arguments, and the
|
||||
* first argument is not undefined, the argument is converted
|
||||
* to a string as used as the filename.<p>
|
||||
*
|
||||
* Otherwise System.in or System.out is assumed as appropriate
|
||||
* to the use.
|
||||
*/
|
||||
public static Scriptable jsConstructor(Context cx, Object[] args,
|
||||
Function ctorObj,
|
||||
boolean inNewExpr)
|
||||
{
|
||||
File result = new File();
|
||||
if (args.length == 0 || args[0] == Context.getUndefinedValue()) {
|
||||
result.name = "";
|
||||
result.file = null;
|
||||
} else {
|
||||
result.name = Context.toString(args[0]);
|
||||
result.file = new java.io.File(result.name);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of this JavaScript class, "File".
|
||||
*/
|
||||
public String getClassName() {
|
||||
return "File";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the file.
|
||||
*
|
||||
* Used to define the "name" property.
|
||||
*/
|
||||
public String jsGet_name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the remaining lines in the file and return them in an array.
|
||||
*
|
||||
* Implements a JavaScript function.<p>
|
||||
*
|
||||
* This is a good example of creating a new array and setting
|
||||
* elements in that array.
|
||||
*
|
||||
* @exception IOException if an error occurred while accessing the file
|
||||
* associated with this object
|
||||
* @exception JavaScriptException if a JavaScript exception occurred
|
||||
* while creating the result array
|
||||
*/
|
||||
public Object jsFunction_readLines()
|
||||
throws IOException, JavaScriptException
|
||||
{
|
||||
Vector v = new Vector();
|
||||
String s;
|
||||
while ((s = jsFunction_readLine()) != null) {
|
||||
v.addElement(s);
|
||||
}
|
||||
Object[] lines = new Object[v.size()];
|
||||
v.copyInto(lines);
|
||||
|
||||
Scriptable scope = ScriptableObject.getTopLevelScope(this);
|
||||
Context cx = Context.getCurrentContext();
|
||||
return cx.newObject(scope, "Array", lines);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a line.
|
||||
*
|
||||
* Implements a JavaScript function.
|
||||
* @exception IOException if an error occurred while accessing the file
|
||||
* associated with this object, or EOFException if the object
|
||||
* reached the end of the file
|
||||
*/
|
||||
public String jsFunction_readLine() throws IOException {
|
||||
return getReader().readLine();
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a character.
|
||||
*
|
||||
* @exception IOException if an error occurred while accessing the file
|
||||
* associated with this object, or EOFException if the object
|
||||
* reached the end of the file
|
||||
*/
|
||||
public String jsFunction_readChar() throws IOException {
|
||||
int i = getReader().read();
|
||||
if (i == -1)
|
||||
return null;
|
||||
char[] charArray = { (char) i };
|
||||
return new String(charArray);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write strings.
|
||||
*
|
||||
* Implements a JavaScript function. <p>
|
||||
*
|
||||
* This function takes a variable number of arguments, converts
|
||||
* each argument to a string, and writes that string to the file.
|
||||
* @exception IOException if an error occurred while accessing the file
|
||||
* associated with this object
|
||||
*/
|
||||
public static void jsFunction_write(Context cx, Scriptable thisObj,
|
||||
Object[] args, Function funObj)
|
||||
throws IOException
|
||||
{
|
||||
write0(thisObj, args, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write strings and a newline.
|
||||
*
|
||||
* Implements a JavaScript function.
|
||||
* @exception IOException if an error occurred while accessing the file
|
||||
* associated with this object
|
||||
*
|
||||
*/
|
||||
public static void jsFunction_writeLine(Context cx, Scriptable thisObj,
|
||||
Object[] args, Function funObj)
|
||||
throws IOException
|
||||
{
|
||||
write0(thisObj, args, true);
|
||||
}
|
||||
|
||||
public int jsGet_lineNumber()
|
||||
throws FileNotFoundException
|
||||
{
|
||||
return getReader().getLineNumber();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the file. It may be reopened.
|
||||
*
|
||||
* Implements a JavaScript function.
|
||||
* @exception IOException if an error occurred while accessing the file
|
||||
* associated with this object
|
||||
*/
|
||||
public void jsFunction_close() throws IOException {
|
||||
if (reader != null) {
|
||||
reader.close();
|
||||
reader = null;
|
||||
} else if (writer != null) {
|
||||
writer.close();
|
||||
writer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalizer.
|
||||
*
|
||||
* Close the file when this object is collected.
|
||||
*/
|
||||
public void finalize() {
|
||||
try {
|
||||
jsFunction_close();
|
||||
}
|
||||
catch (IOException e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Java reader.
|
||||
*/
|
||||
public Object jsFunction_getReader() {
|
||||
if (reader == null)
|
||||
return null;
|
||||
// Here we use toObject() to "wrap" the BufferedReader object
|
||||
// in a Scriptable object so that it can be manipulated by
|
||||
// JavaScript.
|
||||
Scriptable parent = ScriptableObject.getTopLevelScope(this);
|
||||
return Context.toObject(reader, parent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Java writer.
|
||||
*
|
||||
* @see File#jsFunction_getReader
|
||||
*
|
||||
*/
|
||||
public Object jsFunction_getWriter() {
|
||||
if (writer == null)
|
||||
return null;
|
||||
Scriptable parent = ScriptableObject.getTopLevelScope(this);
|
||||
return Context.toObject(writer, parent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the reader, checking that we're not already writing this file.
|
||||
*/
|
||||
private LineNumberReader getReader() throws FileNotFoundException {
|
||||
if (writer != null) {
|
||||
throw Context.reportRuntimeError("already writing file \""
|
||||
+ name
|
||||
+ "\"");
|
||||
}
|
||||
if (reader == null)
|
||||
reader = new LineNumberReader(file == null
|
||||
? new InputStreamReader(System.in)
|
||||
: new FileReader(file));
|
||||
return reader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform the guts of write and writeLine.
|
||||
*
|
||||
* Since the two functions differ only in whether they write a
|
||||
* newline character, move the code into a common subroutine.
|
||||
*
|
||||
*/
|
||||
private static void write0(Scriptable thisObj, Object[] args, boolean eol)
|
||||
throws IOException
|
||||
{
|
||||
File thisFile = checkInstance(thisObj);
|
||||
if (thisFile.reader != null) {
|
||||
throw Context.reportRuntimeError("already writing file \""
|
||||
+ thisFile.name
|
||||
+ "\"");
|
||||
}
|
||||
if (thisFile.writer == null)
|
||||
thisFile.writer = new BufferedWriter(
|
||||
thisFile.file == null ? new OutputStreamWriter(System.out)
|
||||
: new FileWriter(thisFile.file));
|
||||
for (int i=0; i < args.length; i++) {
|
||||
String s = Context.toString(args[i]);
|
||||
thisFile.writer.write(s, 0, s.length());
|
||||
}
|
||||
if (eol)
|
||||
thisFile.writer.newLine();
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform the instanceof check and return the downcasted File object.
|
||||
*
|
||||
* This is necessary since methods may reside in the File.prototype
|
||||
* object and scripts can dynamically alter prototype chains. For example:
|
||||
* <pre>
|
||||
* js> defineClass("File");
|
||||
* js> o = {};
|
||||
* [object Object]
|
||||
* js> o.__proto__ = File.prototype;
|
||||
* [object File]
|
||||
* js> o.write("hi");
|
||||
* js: called on incompatible object
|
||||
* </pre>
|
||||
* The runtime will take care of such checks when non-static Java methods
|
||||
* are defined as JavaScript functions.
|
||||
*/
|
||||
private static File checkInstance(Scriptable obj) {
|
||||
if (obj == null || !(obj instanceof File)) {
|
||||
throw Context.reportRuntimeError("called on incompatible object");
|
||||
}
|
||||
return (File) obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Some private data for this class.
|
||||
*/
|
||||
private String name;
|
||||
private java.io.File file; // may be null, meaning to use System.out or .in
|
||||
private LineNumberReader reader;
|
||||
private BufferedWriter writer;
|
||||
}
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
import org.mozilla.javascript.*;
|
||||
|
||||
/**
|
||||
* An example host object class.
|
||||
*
|
||||
* Here's a shell session showing the Foo object in action:
|
||||
* <pre>
|
||||
* js> defineClass("Foo")
|
||||
* js> foo = new Foo(); <i>A constructor call, see <a href="#Foo">Foo</a> below.</i>
|
||||
* [object Foo] <i>The "Foo" here comes from <a href"#getClassName">getClassName</a>.</i>
|
||||
* js> foo.counter; <i>The counter property is defined by the <code>defineProperty</code></i>
|
||||
* 0 <i>call below and implemented by the <a href="#getCounter">getCounter</a></i>
|
||||
* js> foo.counter; <i>method below.</i>
|
||||
* 1
|
||||
* js> foo.counter;
|
||||
* 2
|
||||
* js> foo.resetCounter(); <i>Results in a call to <a href="#resetCounter">resetCounter</a>.</i>
|
||||
* js> foo.counter; <i>Now the counter has been reset.</i>
|
||||
* 0
|
||||
* js> foo.counter;
|
||||
* 1
|
||||
* js> bar = new Foo(37); <i>Create a new instance.</i>
|
||||
* [object Foo]
|
||||
* js> bar.counter; <i>This instance's counter is distinct from</i>
|
||||
* 37 <i>the other instance's counter.</i>
|
||||
* js> foo.varargs(3, "hi"); <i>Calls <a href="#varargs">varargs</a>.</i>
|
||||
* this = [object Foo]; args = [3, hi]
|
||||
* js> foo[7] = 34; <i>Since we extended ScriptableObject, we get</i>
|
||||
* 34 <i>all the behavior of a JavaScript object</i>
|
||||
* js> foo.a = 23; <i>for free.</i>
|
||||
* 23
|
||||
* js> foo.a + foo[7];
|
||||
* 57
|
||||
* js>
|
||||
* </pre>
|
||||
*
|
||||
* @see org.mozilla.javascript.Context
|
||||
* @see org.mozilla.javascript.Scriptable
|
||||
* @see org.mozilla.javascript.ScriptableObject
|
||||
*
|
||||
* @author Norris Boyd
|
||||
*/
|
||||
|
||||
public class Foo extends ScriptableObject {
|
||||
|
||||
/**
|
||||
* 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".
|
||||
*/
|
||||
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.
|
||||
* <p>
|
||||
* 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. <p>
|
||||
* @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.
|
||||
*
|
||||
* @exception ThreadAssociationException if the current
|
||||
* thread is not associated with a Context
|
||||
* @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;
|
||||
}
|
||||
|
||||
@@ -1,276 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
import org.mozilla.javascript.*;
|
||||
import java.util.Vector;
|
||||
|
||||
/**
|
||||
* 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:
|
||||
* <pre>
|
||||
* js> defineClass("Matrix")
|
||||
* js> m = new Matrix(2); <i>A constructor call, see <a href="#Matrix">Matrix</a> below.</i>
|
||||
* [object Matrix] <i>The "Matrix" here comes from <a href"#getClassName">getClassName</a>.</i>
|
||||
* js> version(120); <i>switch to JavaScript1.2 to see arrays better</i>
|
||||
* 0
|
||||
* js> m[0][0] = 3;
|
||||
* 3
|
||||
* js> m[0]; <i>an array was created automatically!</i>
|
||||
* [3]
|
||||
* js> m[1]; <i>array is created even if we don't set a value</i>
|
||||
* []
|
||||
* js> m.dim; <i>we can access the "dim" property</i>
|
||||
* 2
|
||||
* js> m.dim = 3;
|
||||
* 3
|
||||
* js> m.dim; <i>but not modify it</i>
|
||||
* 2
|
||||
* </pre>
|
||||
*
|
||||
* @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;
|
||||
v = new Vector();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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".
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* Look up the element in the associated vector and return
|
||||
* it if it exists. If it doesn't exist, create it.<p>
|
||||
* @param index the index of the integral property
|
||||
* @param start the object where the lookup began
|
||||
*/
|
||||
public Object get(int index, Scriptable start) {
|
||||
if (index >= v.size())
|
||||
v.setSize(index+1);
|
||||
Object result = v.elementAt(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);
|
||||
}
|
||||
v.setElementAt(result, index);
|
||||
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 <code>this</code> appears in <code>value</code>'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 Vector v;
|
||||
private Scriptable prototype, parent;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
<html>
|
||||
<body>
|
||||
This is the NervousText applet in javascript:
|
||||
<applet archive="js.jar" code=NervousText width=200 height=50 >
|
||||
</applet>
|
||||
|
||||
<hr>
|
||||
The test assumes that applet code is generated with:
|
||||
<pre>
|
||||
java -classpath js.jar org.mozilla.javascript.tools.jsc.Main \
|
||||
-extends java.applet.Applet \
|
||||
-implements java.lang.Runnable \
|
||||
NervousText.js
|
||||
</pre>
|
||||
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.
|
||||
<p>
|
||||
The test also assumes that js.jar from Rhino distribution is available in the same directory.
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,75 +0,0 @@
|
||||
// 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<separated.length;i++)
|
||||
{
|
||||
x_coord = Math.random()*10+15*i;
|
||||
y_coord = Math.random()*10+36;
|
||||
g.drawChars(separated, i,1,x_coord,y_coord);
|
||||
}
|
||||
}
|
||||
|
||||
/* Added by kwalrath. */
|
||||
function mouseDown(evt, x, y) {
|
||||
if (threadSuspended) {
|
||||
killme.resume();
|
||||
}
|
||||
else {
|
||||
killme.suspend();
|
||||
}
|
||||
threadSuspended = !threadSuspended;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Norris Boyd
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
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.
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* The PrimitiveWrapFactory is enabled on a Context by calling setWrapFactory
|
||||
* on that context.
|
||||
*/
|
||||
public class PrimitiveWrapFactory extends WrapFactory {
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
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[])
|
||||
throws JavaScriptException
|
||||
{
|
||||
// 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, "<cmd>", 1, null);
|
||||
|
||||
// Convert the result to a string and print it.
|
||||
System.err.println(cx.toString(result));
|
||||
|
||||
} finally {
|
||||
// Exit from the context.
|
||||
Context.exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
import org.mozilla.javascript.*;
|
||||
|
||||
/**
|
||||
* RunScript2: Like RunScript, but reflects the System.out into JavaScript.
|
||||
*
|
||||
* @author Norris Boyd
|
||||
*/
|
||||
public class RunScript2 {
|
||||
public static void main(String args[])
|
||||
throws JavaScriptException
|
||||
{
|
||||
Context cx = Context.enter();
|
||||
try {
|
||||
Scriptable scope = cx.initStandardObjects();
|
||||
|
||||
// Add a global variable "out" that is a JavaScript reflection
|
||||
// of System.out
|
||||
Scriptable jsArgs = Context.toObject(System.out, scope);
|
||||
scope.put("out", scope, jsArgs);
|
||||
|
||||
String s = "";
|
||||
for (int i=0; i < args.length; i++) {
|
||||
s += args[i];
|
||||
}
|
||||
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
|
||||
System.err.println(cx.toString(result));
|
||||
} finally {
|
||||
Context.exit();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
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[])
|
||||
throws JavaScriptException
|
||||
{
|
||||
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 colected. We'll ignore the result.
|
||||
cx.evaluateString(scope, s, "<cmd>", 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
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, "<cmd>", 1, null);
|
||||
System.err.println(cx.toString(result));
|
||||
} finally {
|
||||
Context.exit();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,345 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
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
|
||||
{
|
||||
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" };
|
||||
try {
|
||||
shell.defineFunctionProperties(names, Shell.class,
|
||||
ScriptableObject.DONTENUM);
|
||||
} catch (PropertyException e) {
|
||||
throw new Error(e.getMessage());
|
||||
}
|
||||
|
||||
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 = args;
|
||||
if (args.length > 0) {
|
||||
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 = cx.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");
|
||||
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 = (double) cx.getLanguageVersion();
|
||||
if (args.length > 0) {
|
||||
double d = cx.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, cx.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 = "<stdin>";
|
||||
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 != cx.getUndefinedValue()) {
|
||||
System.err.println(cx.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());
|
||||
}
|
||||
}
|
||||
}
|
||||
System.gc();
|
||||
}
|
||||
|
||||
private static void p(String s) {
|
||||
System.out.println(s);
|
||||
}
|
||||
|
||||
private boolean quitting;
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
/*
|
||||
* SwingApplication.js - a translation into JavaScript of
|
||||
* SwingApplication.java, a java.sun.com Swing example.
|
||||
*
|
||||
* @author Roger E Critchlow, Jr.
|
||||
*/
|
||||
|
||||
importPackage(Packages.javax.swing);
|
||||
importPackage(Packages.java.awt);
|
||||
importPackage(Packages.java.awt.event);
|
||||
|
||||
function createComponents() {
|
||||
var labelPrefix = "Number of button clicks: ";
|
||||
var numClicks = 0;
|
||||
var label = new JLabel(labelPrefix + numClicks);
|
||||
var button = new JButton("I'm a Swing button!");
|
||||
button.mnemonic = KeyEvent.VK_I;
|
||||
// Since Rhino 1.5R5 JS functions can be passed to Java method if
|
||||
// corresponding argument type is Java interface with single method.
|
||||
button.addActionListener(function() {
|
||||
numClicks += 1;
|
||||
label.setText(labelPrefix + numClicks);
|
||||
});
|
||||
label.setLabelFor(button);
|
||||
|
||||
/*
|
||||
* An easy way to put space between a top-level container
|
||||
* and its contents is to put the contents in a JPanel
|
||||
* that has an "empty" border.
|
||||
*/
|
||||
var pane = new JPanel();
|
||||
pane.border = BorderFactory.createEmptyBorder(30, //top
|
||||
30, //left
|
||||
10, //bottom
|
||||
30); //right
|
||||
pane.setLayout(new GridLayout(0, 1));
|
||||
pane.add(button);
|
||||
pane.add(label);
|
||||
|
||||
return pane;
|
||||
}
|
||||
|
||||
try {
|
||||
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
|
||||
} catch (e) { }
|
||||
|
||||
//Create the top-level container and add contents to it.
|
||||
var frame = new JFrame("SwingApplication");
|
||||
frame.getContentPane().add(createComponents(), BorderLayout.CENTER);
|
||||
|
||||
//Finish setting up the frame, and show it.
|
||||
frame.addWindowListener(new WindowAdapter({
|
||||
windowClosing : function() {
|
||||
java.lang.System.exit(0);
|
||||
}
|
||||
}) );
|
||||
frame.pack();
|
||||
frame.setVisible(true);
|
||||
|
||||
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Norris Boyd
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* <p>
|
||||
* 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.");
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
|
||||
*
|
||||
* The contents of this file are subject to the Netscape 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/NPL/
|
||||
*
|
||||
* 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 Netscape are
|
||||
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Patrick Beard
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU Public License (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 NPL, indicate your decision by
|
||||
* deleting the provisions above and replace 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 NPL or the GPL.
|
||||
*/
|
||||
|
||||
/*
|
||||
enum.js
|
||||
|
||||
Implementing the interface java.util.Enumeration using the new syntax.
|
||||
Note that this syntax is experimental only, and hasn't been approved
|
||||
by ECMA.
|
||||
The same functionality can be had without the new syntax using the
|
||||
uglier syntax:
|
||||
|
||||
var elements = new JavaAdapter(java.util.Enumeration, {
|
||||
index: 0, elements: array,
|
||||
hasMoreElements: function ...
|
||||
nextElement: function ...
|
||||
});
|
||||
|
||||
by Patrick C. Beard.
|
||||
*/
|
||||
|
||||
// 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());
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user