Merge
This commit is contained in:
commit
2152b58b60
1
.hgtags
1
.hgtags
@ -132,3 +132,4 @@ bc5710332b294676661103bb20d47d2ea3ba8def jdk8-b07
|
||||
24ee504f80412770c6874836cd9e55b536427b1d jdk8-b08
|
||||
fbf3cabc9e3bb1fcf710941d777cb0400505fbe6 jdk8-b09
|
||||
f651ce87127980c58e3599daba964eba2f3b4026 jdk8-b10
|
||||
cc1f5ce8e504d350e0b0c28c5f84333f8d540132 jdk8-b11
|
||||
|
@ -132,3 +132,4 @@ b910aac18c772b823b1f7da03e2c6528725cc6de jdk8-b05
|
||||
fb1bc13260d76447e269e843859eb593fe2a8ab2 jdk8-b08
|
||||
8adb70647b5af5273dfe6a540f07be667cd50216 jdk8-b09
|
||||
a6c4c248e8fa350c35014fa94bab5ac1a1ac3299 jdk8-b10
|
||||
1defbc57940a56f0aa41e9dee87b71e8c8b71103 jdk8-b11
|
||||
|
@ -132,3 +132,4 @@ cc1b599b986a37cb57de4584c5e58169766ca535 jdk8-b05
|
||||
0d52b1c87aa8fdea7fdc9c4126ea58f95ca6b351 jdk8-b08
|
||||
a891732c1a83082177ff7a4cf1506068d9cc0a47 jdk8-b09
|
||||
cda87f7fefcee3b89742a57ce5ad9b03a54c210d jdk8-b10
|
||||
0199e4fef5cc2bd234c65b93220459ef7a3bb3b1 jdk8-b11
|
||||
|
@ -193,3 +193,5 @@ da883b9e6d3788057f9577e72712998ed82c9b7e hs23-b01
|
||||
e4f412d2b75d2c797acff965aa2c420e3d358f09 hs23-b02
|
||||
d815de2e85e511b7deab2a83cf80c0224d011da9 jdk8-b10
|
||||
4d3850d9d326ac3a9bee2d867727e954322d014e hs23-b03
|
||||
4538caeef7b6cbd4302bebced805d65e68ccf301 jdk8-b11
|
||||
6534482ff68ad79066dfe15dfb6d8905f09681bd hs23-b04
|
||||
|
@ -35,7 +35,7 @@ HOTSPOT_VM_COPYRIGHT=Copyright 2011
|
||||
|
||||
HS_MAJOR_VER=23
|
||||
HS_MINOR_VER=0
|
||||
HS_BUILD_NUMBER=03
|
||||
HS_BUILD_NUMBER=04
|
||||
|
||||
JDK_MAJOR_VER=1
|
||||
JDK_MINOR_VER=8
|
||||
|
@ -62,7 +62,7 @@ void CompactibleFreeListSpace::set_cms_values() {
|
||||
MinChunkSize = numQuanta(sizeof(FreeChunk), MinObjAlignmentInBytes) * MinObjAlignment;
|
||||
|
||||
assert(IndexSetStart == 0 && IndexSetStride == 0, "already set");
|
||||
IndexSetStart = MinObjAlignment;
|
||||
IndexSetStart = (int) MinChunkSize;
|
||||
IndexSetStride = MinObjAlignment;
|
||||
}
|
||||
|
||||
@ -138,7 +138,7 @@ CompactibleFreeListSpace::CompactibleFreeListSpace(BlockOffsetSharedArray* bs,
|
||||
} else {
|
||||
_fitStrategy = FreeBlockStrategyNone;
|
||||
}
|
||||
checkFreeListConsistency();
|
||||
check_free_list_consistency();
|
||||
|
||||
// Initialize locks for parallel case.
|
||||
|
||||
@ -1358,17 +1358,29 @@ FreeChunk* CompactibleFreeListSpace::getChunkFromGreater(size_t numWords) {
|
||||
ShouldNotReachHere();
|
||||
}
|
||||
|
||||
bool CompactibleFreeListSpace::verifyChunkInIndexedFreeLists(FreeChunk* fc)
|
||||
const {
|
||||
bool CompactibleFreeListSpace::verifyChunkInIndexedFreeLists(FreeChunk* fc) const {
|
||||
assert(fc->size() < IndexSetSize, "Size of chunk is too large");
|
||||
return _indexedFreeList[fc->size()].verifyChunkInFreeLists(fc);
|
||||
}
|
||||
|
||||
bool CompactibleFreeListSpace::verify_chunk_is_linear_alloc_block(FreeChunk* fc) const {
|
||||
assert((_smallLinearAllocBlock._ptr != (HeapWord*)fc) ||
|
||||
(_smallLinearAllocBlock._word_size == fc->size()),
|
||||
"Linear allocation block shows incorrect size");
|
||||
return ((_smallLinearAllocBlock._ptr == (HeapWord*)fc) &&
|
||||
(_smallLinearAllocBlock._word_size == fc->size()));
|
||||
}
|
||||
|
||||
// Check if the purported free chunk is present either as a linear
|
||||
// allocation block, the size-indexed table of (smaller) free blocks,
|
||||
// or the larger free blocks kept in the binary tree dictionary.
|
||||
bool CompactibleFreeListSpace::verifyChunkInFreeLists(FreeChunk* fc) const {
|
||||
if (fc->size() >= IndexSetSize) {
|
||||
return dictionary()->verifyChunkInFreeLists(fc);
|
||||
} else {
|
||||
if (verify_chunk_is_linear_alloc_block(fc)) {
|
||||
return true;
|
||||
} else if (fc->size() < IndexSetSize) {
|
||||
return verifyChunkInIndexedFreeLists(fc);
|
||||
} else {
|
||||
return dictionary()->verifyChunkInFreeLists(fc);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2495,7 +2507,8 @@ void CompactibleFreeListSpace::verifyIndexedFreeList(size_t size) const {
|
||||
FreeChunk* tail = _indexedFreeList[size].tail();
|
||||
size_t num = _indexedFreeList[size].count();
|
||||
size_t n = 0;
|
||||
guarantee((size % 2 == 0) || fc == NULL, "Odd slots should be empty");
|
||||
guarantee(((size >= MinChunkSize) && (size % IndexSetStride == 0)) || fc == NULL,
|
||||
"Slot should have been empty");
|
||||
for (; fc != NULL; fc = fc->next(), n++) {
|
||||
guarantee(fc->size() == size, "Size inconsistency");
|
||||
guarantee(fc->isFree(), "!free?");
|
||||
@ -2506,14 +2519,14 @@ void CompactibleFreeListSpace::verifyIndexedFreeList(size_t size) const {
|
||||
}
|
||||
|
||||
#ifndef PRODUCT
|
||||
void CompactibleFreeListSpace::checkFreeListConsistency() const {
|
||||
void CompactibleFreeListSpace::check_free_list_consistency() const {
|
||||
assert(_dictionary->minSize() <= IndexSetSize,
|
||||
"Some sizes can't be allocated without recourse to"
|
||||
" linear allocation buffers");
|
||||
assert(MIN_TREE_CHUNK_SIZE*HeapWordSize == sizeof(TreeChunk),
|
||||
"else MIN_TREE_CHUNK_SIZE is wrong");
|
||||
assert((IndexSetStride == 2 && IndexSetStart == 2) ||
|
||||
(IndexSetStride == 1 && IndexSetStart == 1), "just checking");
|
||||
assert((IndexSetStride == 2 && IndexSetStart == 4) || // 32-bit
|
||||
(IndexSetStride == 1 && IndexSetStart == 3), "just checking"); // 64-bit
|
||||
assert((IndexSetStride != 2) || (MinChunkSize % 2 == 0),
|
||||
"Some for-loops may be incorrectly initialized");
|
||||
assert((IndexSetStride != 2) || (IndexSetSize % 2 == 1),
|
||||
@ -2688,33 +2701,27 @@ void CFLS_LAB::compute_desired_plab_size() {
|
||||
}
|
||||
}
|
||||
|
||||
// If this is changed in the future to allow parallel
|
||||
// access, one would need to take the FL locks and,
|
||||
// depending on how it is used, stagger access from
|
||||
// parallel threads to reduce contention.
|
||||
void CFLS_LAB::retire(int tid) {
|
||||
// We run this single threaded with the world stopped;
|
||||
// so no need for locks and such.
|
||||
#define CFLS_LAB_PARALLEL_ACCESS 0
|
||||
NOT_PRODUCT(Thread* t = Thread::current();)
|
||||
assert(Thread::current()->is_VM_thread(), "Error");
|
||||
assert(CompactibleFreeListSpace::IndexSetStart == CompactibleFreeListSpace::IndexSetStride,
|
||||
"Will access to uninitialized slot below");
|
||||
#if CFLS_LAB_PARALLEL_ACCESS
|
||||
for (size_t i = CompactibleFreeListSpace::IndexSetSize - 1;
|
||||
i > 0;
|
||||
i -= CompactibleFreeListSpace::IndexSetStride) {
|
||||
#else // CFLS_LAB_PARALLEL_ACCESS
|
||||
for (size_t i = CompactibleFreeListSpace::IndexSetStart;
|
||||
i < CompactibleFreeListSpace::IndexSetSize;
|
||||
i += CompactibleFreeListSpace::IndexSetStride) {
|
||||
#endif // !CFLS_LAB_PARALLEL_ACCESS
|
||||
assert(_num_blocks[i] >= (size_t)_indexedFreeList[i].count(),
|
||||
"Can't retire more than what we obtained");
|
||||
if (_num_blocks[i] > 0) {
|
||||
size_t num_retire = _indexedFreeList[i].count();
|
||||
assert(_num_blocks[i] > num_retire, "Should have used at least one");
|
||||
{
|
||||
#if CFLS_LAB_PARALLEL_ACCESS
|
||||
MutexLockerEx x(_cfls->_indexedFreeListParLocks[i],
|
||||
Mutex::_no_safepoint_check_flag);
|
||||
#endif // CFLS_LAB_PARALLEL_ACCESS
|
||||
// MutexLockerEx x(_cfls->_indexedFreeListParLocks[i],
|
||||
// Mutex::_no_safepoint_check_flag);
|
||||
|
||||
// Update globals stats for num_blocks used
|
||||
_global_num_blocks[i] += (_num_blocks[i] - num_retire);
|
||||
_global_num_workers[i]++;
|
||||
|
@ -502,10 +502,14 @@ class CompactibleFreeListSpace: public CompactibleSpace {
|
||||
void verifyFreeLists() const PRODUCT_RETURN;
|
||||
void verifyIndexedFreeLists() const;
|
||||
void verifyIndexedFreeList(size_t size) const;
|
||||
// verify that the given chunk is in the free lists.
|
||||
// Verify that the given chunk is in the free lists:
|
||||
// i.e. either the binary tree dictionary, the indexed free lists
|
||||
// or the linear allocation block.
|
||||
bool verifyChunkInFreeLists(FreeChunk* fc) const;
|
||||
// Verify that the given chunk is the linear allocation block
|
||||
bool verify_chunk_is_linear_alloc_block(FreeChunk* fc) const;
|
||||
// Do some basic checks on the the free lists.
|
||||
void checkFreeListConsistency() const PRODUCT_RETURN;
|
||||
void check_free_list_consistency() const PRODUCT_RETURN;
|
||||
|
||||
// Printing support
|
||||
void dump_at_safepoint_with_locks(CMSCollector* c, outputStream* st);
|
||||
|
@ -147,12 +147,8 @@ void ConcurrentMarkThread::run() {
|
||||
}
|
||||
}
|
||||
} while (cm()->restart_for_overflow());
|
||||
|
||||
double counting_start_time = os::elapsedVTime();
|
||||
|
||||
// YSR: These look dubious (i.e. redundant) !!! FIX ME
|
||||
slt()->manipulatePLL(SurrogateLockerThread::acquirePLL);
|
||||
slt()->manipulatePLL(SurrogateLockerThread::releaseAndNotifyPLL);
|
||||
|
||||
if (!cm()->has_aborted()) {
|
||||
double count_start_sec = os::elapsedTime();
|
||||
if (PrintGC) {
|
||||
@ -175,6 +171,7 @@ void ConcurrentMarkThread::run() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double end_time = os::elapsedVTime();
|
||||
_vtime_count_accum += (end_time - counting_start_time);
|
||||
// Update the total virtual time before doing this, since it will try
|
||||
@ -335,13 +332,15 @@ void ConcurrentMarkThread::sleepBeforeNextCycle() {
|
||||
clear_started();
|
||||
}
|
||||
|
||||
// Note: this method, although exported by the ConcurrentMarkSweepThread,
|
||||
// which is a non-JavaThread, can only be called by a JavaThread.
|
||||
// Currently this is done at vm creation time (post-vm-init) by the
|
||||
// main/Primordial (Java)Thread.
|
||||
// XXX Consider changing this in the future to allow the CMS thread
|
||||
// Note: As is the case with CMS - this method, although exported
|
||||
// by the ConcurrentMarkThread, which is a non-JavaThread, can only
|
||||
// be called by a JavaThread. Currently this is done at vm creation
|
||||
// time (post-vm-init) by the main/Primordial (Java)Thread.
|
||||
// XXX Consider changing this in the future to allow the CM thread
|
||||
// itself to create this thread?
|
||||
void ConcurrentMarkThread::makeSurrogateLockerThread(TRAPS) {
|
||||
assert(UseG1GC, "SLT thread needed only for concurrent GC");
|
||||
assert(THREAD->is_Java_thread(), "must be a Java thread");
|
||||
assert(_slt == NULL, "SLT already created");
|
||||
_slt = SurrogateLockerThread::make(THREAD);
|
||||
}
|
||||
|
@ -5502,34 +5502,36 @@ void G1CollectedHeap::cleanUpCardTable() {
|
||||
CardTableModRefBS* ct_bs = (CardTableModRefBS*) (barrier_set());
|
||||
double start = os::elapsedTime();
|
||||
|
||||
// Iterate over the dirty cards region list.
|
||||
G1ParCleanupCTTask cleanup_task(ct_bs, this);
|
||||
{
|
||||
// Iterate over the dirty cards region list.
|
||||
G1ParCleanupCTTask cleanup_task(ct_bs, this);
|
||||
|
||||
if (ParallelGCThreads > 0) {
|
||||
set_par_threads(workers()->total_workers());
|
||||
workers()->run_task(&cleanup_task);
|
||||
set_par_threads(0);
|
||||
} else {
|
||||
while (_dirty_cards_region_list) {
|
||||
HeapRegion* r = _dirty_cards_region_list;
|
||||
cleanup_task.clear_cards(r);
|
||||
_dirty_cards_region_list = r->get_next_dirty_cards_region();
|
||||
if (_dirty_cards_region_list == r) {
|
||||
// The last region.
|
||||
_dirty_cards_region_list = NULL;
|
||||
if (ParallelGCThreads > 0) {
|
||||
set_par_threads(workers()->total_workers());
|
||||
workers()->run_task(&cleanup_task);
|
||||
set_par_threads(0);
|
||||
} else {
|
||||
while (_dirty_cards_region_list) {
|
||||
HeapRegion* r = _dirty_cards_region_list;
|
||||
cleanup_task.clear_cards(r);
|
||||
_dirty_cards_region_list = r->get_next_dirty_cards_region();
|
||||
if (_dirty_cards_region_list == r) {
|
||||
// The last region.
|
||||
_dirty_cards_region_list = NULL;
|
||||
}
|
||||
r->set_next_dirty_cards_region(NULL);
|
||||
}
|
||||
r->set_next_dirty_cards_region(NULL);
|
||||
}
|
||||
#ifndef PRODUCT
|
||||
if (G1VerifyCTCleanup || VerifyAfterGC) {
|
||||
G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs);
|
||||
heap_region_iterate(&cleanup_verifier);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
double elapsed = os::elapsedTime() - start;
|
||||
g1_policy()->record_clear_ct_time(elapsed * 1000.0);
|
||||
#ifndef PRODUCT
|
||||
if (G1VerifyCTCleanup || VerifyAfterGC) {
|
||||
G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs);
|
||||
heap_region_iterate(&cleanup_verifier);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void G1CollectedHeap::free_collection_set(HeapRegion* cs_head) {
|
||||
|
@ -320,6 +320,7 @@ G1CollectorPolicy::G1CollectorPolicy() :
|
||||
_par_last_termination_attempts = new double[_parallel_gc_threads];
|
||||
_par_last_gc_worker_end_times_ms = new double[_parallel_gc_threads];
|
||||
_par_last_gc_worker_times_ms = new double[_parallel_gc_threads];
|
||||
_par_last_gc_worker_other_times_ms = new double[_parallel_gc_threads];
|
||||
|
||||
// start conservatively
|
||||
_expensive_region_limit_ms = 0.5 * (double) MaxGCPauseMillis;
|
||||
@ -497,7 +498,6 @@ void G1CollectorPolicy::init() {
|
||||
initialize_gc_policy_counters();
|
||||
|
||||
G1YoungGenSizer sizer;
|
||||
size_t initial_region_num = sizer.initial_young_region_num();
|
||||
_min_desired_young_length = sizer.min_young_region_num();
|
||||
_max_desired_young_length = sizer.max_young_region_num();
|
||||
|
||||
@ -511,17 +511,14 @@ void G1CollectorPolicy::init() {
|
||||
}
|
||||
}
|
||||
|
||||
// GenCollectorPolicy guarantees that min <= initial <= max.
|
||||
// Asserting here just to state that we rely on this property.
|
||||
assert(_min_desired_young_length <= _max_desired_young_length, "Invalid min/max young gen size values");
|
||||
assert(initial_region_num <= _max_desired_young_length, "Initial young gen size too large");
|
||||
assert(_min_desired_young_length <= initial_region_num, "Initial young gen size too small");
|
||||
|
||||
set_adaptive_young_list_length(_min_desired_young_length < _max_desired_young_length);
|
||||
if (adaptive_young_list_length()) {
|
||||
_young_list_fixed_length = 0;
|
||||
} else {
|
||||
_young_list_fixed_length = initial_region_num;
|
||||
assert(_min_desired_young_length == _max_desired_young_length, "Min and max young size differ");
|
||||
_young_list_fixed_length = _min_desired_young_length;
|
||||
}
|
||||
_free_regions_at_end_of_collection = _g1->free_regions();
|
||||
update_young_list_target_length();
|
||||
@ -976,6 +973,7 @@ void G1CollectorPolicy::record_collection_pause_start(double start_time_sec,
|
||||
_par_last_termination_attempts[i] = -1234.0;
|
||||
_par_last_gc_worker_end_times_ms[i] = -1234.0;
|
||||
_par_last_gc_worker_times_ms[i] = -1234.0;
|
||||
_par_last_gc_worker_other_times_ms[i] = -1234.0;
|
||||
}
|
||||
#endif
|
||||
|
||||
@ -984,8 +982,10 @@ void G1CollectorPolicy::record_collection_pause_start(double start_time_sec,
|
||||
_cur_aux_times_set[i] = false;
|
||||
}
|
||||
|
||||
_satb_drain_time_set = false;
|
||||
_last_satb_drain_processed_buffers = -1;
|
||||
// These are initialized to zero here and they are set during
|
||||
// the evacuation pause if marking is in progress.
|
||||
_cur_satb_drain_time_ms = 0.0;
|
||||
_last_satb_drain_processed_buffers = 0;
|
||||
|
||||
_last_young_gc_full = false;
|
||||
|
||||
@ -1097,61 +1097,65 @@ void G1CollectorPolicy::print_par_sizes(int level,
|
||||
(int)total, (int)avg, (int)min, (int)max, (int)max - (int)min);
|
||||
}
|
||||
|
||||
void G1CollectorPolicy::print_stats (int level,
|
||||
const char* str,
|
||||
double value) {
|
||||
void G1CollectorPolicy::print_stats(int level,
|
||||
const char* str,
|
||||
double value) {
|
||||
LineBuffer(level).append_and_print_cr("[%s: %5.1lf ms]", str, value);
|
||||
}
|
||||
|
||||
void G1CollectorPolicy::print_stats (int level,
|
||||
const char* str,
|
||||
int value) {
|
||||
void G1CollectorPolicy::print_stats(int level,
|
||||
const char* str,
|
||||
int value) {
|
||||
LineBuffer(level).append_and_print_cr("[%s: %d]", str, value);
|
||||
}
|
||||
|
||||
double G1CollectorPolicy::avg_value (double* data) {
|
||||
double G1CollectorPolicy::avg_value(double* data) {
|
||||
if (G1CollectedHeap::use_parallel_gc_threads()) {
|
||||
double ret = 0.0;
|
||||
for (uint i = 0; i < ParallelGCThreads; ++i)
|
||||
for (uint i = 0; i < ParallelGCThreads; ++i) {
|
||||
ret += data[i];
|
||||
}
|
||||
return ret / (double) ParallelGCThreads;
|
||||
} else {
|
||||
return data[0];
|
||||
}
|
||||
}
|
||||
|
||||
double G1CollectorPolicy::max_value (double* data) {
|
||||
double G1CollectorPolicy::max_value(double* data) {
|
||||
if (G1CollectedHeap::use_parallel_gc_threads()) {
|
||||
double ret = data[0];
|
||||
for (uint i = 1; i < ParallelGCThreads; ++i)
|
||||
if (data[i] > ret)
|
||||
for (uint i = 1; i < ParallelGCThreads; ++i) {
|
||||
if (data[i] > ret) {
|
||||
ret = data[i];
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
} else {
|
||||
return data[0];
|
||||
}
|
||||
}
|
||||
|
||||
double G1CollectorPolicy::sum_of_values (double* data) {
|
||||
double G1CollectorPolicy::sum_of_values(double* data) {
|
||||
if (G1CollectedHeap::use_parallel_gc_threads()) {
|
||||
double sum = 0.0;
|
||||
for (uint i = 0; i < ParallelGCThreads; i++)
|
||||
for (uint i = 0; i < ParallelGCThreads; i++) {
|
||||
sum += data[i];
|
||||
}
|
||||
return sum;
|
||||
} else {
|
||||
return data[0];
|
||||
}
|
||||
}
|
||||
|
||||
double G1CollectorPolicy::max_sum (double* data1,
|
||||
double* data2) {
|
||||
double G1CollectorPolicy::max_sum(double* data1, double* data2) {
|
||||
double ret = data1[0] + data2[0];
|
||||
|
||||
if (G1CollectedHeap::use_parallel_gc_threads()) {
|
||||
for (uint i = 1; i < ParallelGCThreads; ++i) {
|
||||
double data = data1[i] + data2[i];
|
||||
if (data > ret)
|
||||
if (data > ret) {
|
||||
ret = data;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
@ -1251,6 +1255,10 @@ void G1CollectorPolicy::record_collection_pause_end() {
|
||||
|
||||
_n_pauses++;
|
||||
|
||||
// These values are used to update the summary information that is
|
||||
// displayed when TraceGen0Time is enabled, and are output as part
|
||||
// of the PrintGCDetails output, in the non-parallel case.
|
||||
|
||||
double ext_root_scan_time = avg_value(_par_last_ext_root_scan_times_ms);
|
||||
double mark_stack_scan_time = avg_value(_par_last_mark_stack_scan_times_ms);
|
||||
double update_rs_time = avg_value(_par_last_update_rs_times_ms);
|
||||
@ -1260,42 +1268,68 @@ void G1CollectorPolicy::record_collection_pause_end() {
|
||||
double obj_copy_time = avg_value(_par_last_obj_copy_times_ms);
|
||||
double termination_time = avg_value(_par_last_termination_times_ms);
|
||||
|
||||
double parallel_known_time = update_rs_time +
|
||||
ext_root_scan_time +
|
||||
mark_stack_scan_time +
|
||||
scan_rs_time +
|
||||
obj_copy_time +
|
||||
termination_time;
|
||||
double known_time = ext_root_scan_time +
|
||||
mark_stack_scan_time +
|
||||
update_rs_time +
|
||||
scan_rs_time +
|
||||
obj_copy_time;
|
||||
|
||||
double parallel_other_time = _cur_collection_par_time_ms - parallel_known_time;
|
||||
double other_time_ms = elapsed_ms;
|
||||
|
||||
PauseSummary* summary = _summary;
|
||||
// Subtract the SATB drain time. It's initialized to zero at the
|
||||
// start of the pause and is updated during the pause if marking
|
||||
// is in progress.
|
||||
other_time_ms -= _cur_satb_drain_time_ms;
|
||||
|
||||
if (parallel) {
|
||||
other_time_ms -= _cur_collection_par_time_ms;
|
||||
} else {
|
||||
other_time_ms -= known_time;
|
||||
}
|
||||
|
||||
// Subtract the time taken to clean the card table from the
|
||||
// current value of "other time"
|
||||
other_time_ms -= _cur_clear_ct_time_ms;
|
||||
|
||||
// TraceGen0Time and TraceGen1Time summary info updating.
|
||||
_all_pause_times_ms->add(elapsed_ms);
|
||||
|
||||
if (update_stats) {
|
||||
_recent_rs_scan_times_ms->add(scan_rs_time);
|
||||
_recent_pause_times_ms->add(elapsed_ms);
|
||||
_recent_rs_sizes->add(rs_size);
|
||||
|
||||
MainBodySummary* body_summary = summary->main_body_summary();
|
||||
guarantee(body_summary != NULL, "should not be null!");
|
||||
_summary->record_total_time_ms(elapsed_ms);
|
||||
_summary->record_other_time_ms(other_time_ms);
|
||||
|
||||
if (_satb_drain_time_set)
|
||||
body_summary->record_satb_drain_time_ms(_cur_satb_drain_time_ms);
|
||||
else
|
||||
body_summary->record_satb_drain_time_ms(0.0);
|
||||
MainBodySummary* body_summary = _summary->main_body_summary();
|
||||
assert(body_summary != NULL, "should not be null!");
|
||||
|
||||
// This will be non-zero iff marking is currently in progress (i.e.
|
||||
// _g1->mark_in_progress() == true) and the currrent pause was not
|
||||
// an initial mark pause. Since the body_summary items are NumberSeqs,
|
||||
// however, they have to be consistent and updated in lock-step with
|
||||
// each other. Therefore we unconditionally record the SATB drain
|
||||
// time - even if it's zero.
|
||||
body_summary->record_satb_drain_time_ms(_cur_satb_drain_time_ms);
|
||||
|
||||
body_summary->record_ext_root_scan_time_ms(ext_root_scan_time);
|
||||
body_summary->record_mark_stack_scan_time_ms(mark_stack_scan_time);
|
||||
body_summary->record_update_rs_time_ms(update_rs_time);
|
||||
body_summary->record_scan_rs_time_ms(scan_rs_time);
|
||||
body_summary->record_obj_copy_time_ms(obj_copy_time);
|
||||
|
||||
if (parallel) {
|
||||
body_summary->record_parallel_time_ms(_cur_collection_par_time_ms);
|
||||
body_summary->record_clear_ct_time_ms(_cur_clear_ct_time_ms);
|
||||
body_summary->record_termination_time_ms(termination_time);
|
||||
|
||||
double parallel_known_time = known_time + termination_time;
|
||||
double parallel_other_time = _cur_collection_par_time_ms - parallel_known_time;
|
||||
body_summary->record_parallel_other_time_ms(parallel_other_time);
|
||||
}
|
||||
|
||||
body_summary->record_mark_closure_time_ms(_mark_closure_time_ms);
|
||||
body_summary->record_clear_ct_time_ms(_cur_clear_ct_time_ms);
|
||||
|
||||
// We exempt parallel collection from this check because Alloc Buffer
|
||||
// fragmentation can produce negative collections. Same with evac
|
||||
@ -1307,6 +1341,7 @@ void G1CollectorPolicy::record_collection_pause_end() {
|
||||
|| _g1->evacuation_failed()
|
||||
|| surviving_bytes <= _collection_set_bytes_used_before,
|
||||
"Or else negative collection!");
|
||||
|
||||
_recent_CS_bytes_used_before->add(_collection_set_bytes_used_before);
|
||||
_recent_CS_bytes_surviving->add(surviving_bytes);
|
||||
|
||||
@ -1357,6 +1392,13 @@ void G1CollectorPolicy::record_collection_pause_end() {
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < _aux_num; ++i) {
|
||||
if (_cur_aux_times_set[i]) {
|
||||
_all_aux_times_ms[i].add(_cur_aux_times_ms[i]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (G1PolicyVerbose > 1) {
|
||||
gclog_or_tty->print_cr(" Recording collection pause(%d)", _n_pauses);
|
||||
}
|
||||
@ -1383,61 +1425,60 @@ void G1CollectorPolicy::record_collection_pause_end() {
|
||||
recent_avg_pause_time_ratio() * 100.0);
|
||||
}
|
||||
|
||||
double other_time_ms = elapsed_ms;
|
||||
|
||||
if (_satb_drain_time_set) {
|
||||
other_time_ms -= _cur_satb_drain_time_ms;
|
||||
}
|
||||
|
||||
if (parallel) {
|
||||
other_time_ms -= _cur_collection_par_time_ms + _cur_clear_ct_time_ms;
|
||||
} else {
|
||||
other_time_ms -=
|
||||
update_rs_time +
|
||||
ext_root_scan_time + mark_stack_scan_time +
|
||||
scan_rs_time + obj_copy_time;
|
||||
}
|
||||
|
||||
// PrintGCDetails output
|
||||
if (PrintGCDetails) {
|
||||
bool print_marking_info =
|
||||
_g1->mark_in_progress() && !last_pause_included_initial_mark;
|
||||
|
||||
gclog_or_tty->print_cr("%s, %1.8lf secs]",
|
||||
(last_pause_included_initial_mark) ? " (initial-mark)" : "",
|
||||
elapsed_ms / 1000.0);
|
||||
|
||||
if (_satb_drain_time_set) {
|
||||
if (print_marking_info) {
|
||||
print_stats(1, "SATB Drain Time", _cur_satb_drain_time_ms);
|
||||
}
|
||||
if (_last_satb_drain_processed_buffers >= 0) {
|
||||
print_stats(2, "Processed Buffers", _last_satb_drain_processed_buffers);
|
||||
}
|
||||
|
||||
if (parallel) {
|
||||
print_stats(1, "Parallel Time", _cur_collection_par_time_ms);
|
||||
print_par_stats(2, "GC Worker Start Time", _par_last_gc_worker_start_times_ms);
|
||||
print_par_stats(2, "GC Worker Start", _par_last_gc_worker_start_times_ms);
|
||||
print_par_stats(2, "Ext Root Scanning", _par_last_ext_root_scan_times_ms);
|
||||
if (print_marking_info) {
|
||||
print_par_stats(2, "Mark Stack Scanning", _par_last_mark_stack_scan_times_ms);
|
||||
}
|
||||
print_par_stats(2, "Update RS", _par_last_update_rs_times_ms);
|
||||
print_par_sizes(3, "Processed Buffers", _par_last_update_rs_processed_buffers);
|
||||
print_par_stats(2, "Ext Root Scanning", _par_last_ext_root_scan_times_ms);
|
||||
print_par_stats(2, "Mark Stack Scanning", _par_last_mark_stack_scan_times_ms);
|
||||
print_par_stats(2, "Scan RS", _par_last_scan_rs_times_ms);
|
||||
print_par_stats(2, "Object Copy", _par_last_obj_copy_times_ms);
|
||||
print_par_stats(2, "Termination", _par_last_termination_times_ms);
|
||||
print_par_sizes(3, "Termination Attempts", _par_last_termination_attempts);
|
||||
print_par_stats(2, "GC Worker End Time", _par_last_gc_worker_end_times_ms);
|
||||
print_par_stats(2, "GC Worker End", _par_last_gc_worker_end_times_ms);
|
||||
|
||||
for (int i = 0; i < _parallel_gc_threads; i++) {
|
||||
_par_last_gc_worker_times_ms[i] = _par_last_gc_worker_end_times_ms[i] - _par_last_gc_worker_start_times_ms[i];
|
||||
}
|
||||
print_par_stats(2, "GC Worker Times", _par_last_gc_worker_times_ms);
|
||||
|
||||
print_stats(2, "Parallel Other", parallel_other_time);
|
||||
print_stats(1, "Clear CT", _cur_clear_ct_time_ms);
|
||||
double worker_known_time = _par_last_ext_root_scan_times_ms[i] +
|
||||
_par_last_mark_stack_scan_times_ms[i] +
|
||||
_par_last_update_rs_times_ms[i] +
|
||||
_par_last_scan_rs_times_ms[i] +
|
||||
_par_last_obj_copy_times_ms[i] +
|
||||
_par_last_termination_times_ms[i];
|
||||
|
||||
_par_last_gc_worker_other_times_ms[i] = _cur_collection_par_time_ms - worker_known_time;
|
||||
}
|
||||
print_par_stats(2, "GC Worker", _par_last_gc_worker_times_ms);
|
||||
print_par_stats(2, "GC Worker Other", _par_last_gc_worker_other_times_ms);
|
||||
} else {
|
||||
print_stats(1, "Update RS", update_rs_time);
|
||||
print_stats(2, "Processed Buffers",
|
||||
(int)update_rs_processed_buffers);
|
||||
print_stats(1, "Ext Root Scanning", ext_root_scan_time);
|
||||
print_stats(1, "Mark Stack Scanning", mark_stack_scan_time);
|
||||
if (print_marking_info) {
|
||||
print_stats(1, "Mark Stack Scanning", mark_stack_scan_time);
|
||||
}
|
||||
print_stats(1, "Update RS", update_rs_time);
|
||||
print_stats(2, "Processed Buffers", (int)update_rs_processed_buffers);
|
||||
print_stats(1, "Scan RS", scan_rs_time);
|
||||
print_stats(1, "Object Copying", obj_copy_time);
|
||||
}
|
||||
print_stats(1, "Clear CT", _cur_clear_ct_time_ms);
|
||||
#ifndef PRODUCT
|
||||
print_stats(1, "Cur Clear CC", _cur_clear_cc_time_ms);
|
||||
print_stats(1, "Cum Clear CC", _cum_clear_cc_time_ms);
|
||||
@ -1461,16 +1502,6 @@ void G1CollectorPolicy::record_collection_pause_end() {
|
||||
}
|
||||
}
|
||||
|
||||
_all_pause_times_ms->add(elapsed_ms);
|
||||
if (update_stats) {
|
||||
summary->record_total_time_ms(elapsed_ms);
|
||||
summary->record_other_time_ms(other_time_ms);
|
||||
}
|
||||
for (int i = 0; i < _aux_num; ++i)
|
||||
if (_cur_aux_times_set[i]) {
|
||||
_all_aux_times_ms[i].add(_cur_aux_times_ms[i]);
|
||||
}
|
||||
|
||||
// Update the efficiency-since-mark vars.
|
||||
double proc_ms = elapsed_ms * (double) _parallel_gc_threads;
|
||||
if (elapsed_ms < MIN_TIMER_GRANULARITY) {
|
||||
@ -2138,17 +2169,17 @@ void G1CollectorPolicy::count_CS_bytes_used() {
|
||||
_g1->collection_set_iterate(&cs_closure);
|
||||
}
|
||||
|
||||
void G1CollectorPolicy::print_summary (int level,
|
||||
const char* str,
|
||||
NumberSeq* seq) const {
|
||||
void G1CollectorPolicy::print_summary(int level,
|
||||
const char* str,
|
||||
NumberSeq* seq) const {
|
||||
double sum = seq->sum();
|
||||
LineBuffer(level + 1).append_and_print_cr("%-24s = %8.2lf s (avg = %8.2lf ms)",
|
||||
str, sum / 1000.0, seq->avg());
|
||||
}
|
||||
|
||||
void G1CollectorPolicy::print_summary_sd (int level,
|
||||
const char* str,
|
||||
NumberSeq* seq) const {
|
||||
void G1CollectorPolicy::print_summary_sd(int level,
|
||||
const char* str,
|
||||
NumberSeq* seq) const {
|
||||
print_summary(level, str, seq);
|
||||
LineBuffer(level + 6).append_and_print_cr("(num = %5d, std dev = %8.2lf ms, max = %8.2lf ms)",
|
||||
seq->num(), seq->sd(), seq->maximum());
|
||||
@ -2211,20 +2242,18 @@ void G1CollectorPolicy::print_summary(PauseSummary* summary) const {
|
||||
print_summary(1, "SATB Drain", body_summary->get_satb_drain_seq());
|
||||
if (parallel) {
|
||||
print_summary(1, "Parallel Time", body_summary->get_parallel_seq());
|
||||
print_summary(2, "Ext Root Scanning", body_summary->get_ext_root_scan_seq());
|
||||
print_summary(2, "Mark Stack Scanning", body_summary->get_mark_stack_scan_seq());
|
||||
print_summary(2, "Update RS", body_summary->get_update_rs_seq());
|
||||
print_summary(2, "Ext Root Scanning",
|
||||
body_summary->get_ext_root_scan_seq());
|
||||
print_summary(2, "Mark Stack Scanning",
|
||||
body_summary->get_mark_stack_scan_seq());
|
||||
print_summary(2, "Scan RS", body_summary->get_scan_rs_seq());
|
||||
print_summary(2, "Object Copy", body_summary->get_obj_copy_seq());
|
||||
print_summary(2, "Termination", body_summary->get_termination_seq());
|
||||
print_summary(2, "Other", body_summary->get_parallel_other_seq());
|
||||
print_summary(2, "Parallel Other", body_summary->get_parallel_other_seq());
|
||||
{
|
||||
NumberSeq* other_parts[] = {
|
||||
body_summary->get_update_rs_seq(),
|
||||
body_summary->get_ext_root_scan_seq(),
|
||||
body_summary->get_mark_stack_scan_seq(),
|
||||
body_summary->get_update_rs_seq(),
|
||||
body_summary->get_scan_rs_seq(),
|
||||
body_summary->get_obj_copy_seq(),
|
||||
body_summary->get_termination_seq()
|
||||
@ -2234,18 +2263,16 @@ void G1CollectorPolicy::print_summary(PauseSummary* summary) const {
|
||||
check_other_times(2, body_summary->get_parallel_other_seq(),
|
||||
&calc_other_times_ms);
|
||||
}
|
||||
print_summary(1, "Mark Closure", body_summary->get_mark_closure_seq());
|
||||
print_summary(1, "Clear CT", body_summary->get_clear_ct_seq());
|
||||
} else {
|
||||
print_summary(1, "Ext Root Scanning", body_summary->get_ext_root_scan_seq());
|
||||
print_summary(1, "Mark Stack Scanning", body_summary->get_mark_stack_scan_seq());
|
||||
print_summary(1, "Update RS", body_summary->get_update_rs_seq());
|
||||
print_summary(1, "Ext Root Scanning",
|
||||
body_summary->get_ext_root_scan_seq());
|
||||
print_summary(1, "Mark Stack Scanning",
|
||||
body_summary->get_mark_stack_scan_seq());
|
||||
print_summary(1, "Scan RS", body_summary->get_scan_rs_seq());
|
||||
print_summary(1, "Object Copy", body_summary->get_obj_copy_seq());
|
||||
}
|
||||
}
|
||||
print_summary(1, "Mark Closure", body_summary->get_mark_closure_seq());
|
||||
print_summary(1, "Clear CT", body_summary->get_clear_ct_seq());
|
||||
print_summary(1, "Other", summary->get_other_seq());
|
||||
{
|
||||
if (body_summary != NULL) {
|
||||
|
@ -74,7 +74,7 @@ class MainBodySummary: public CHeapObj {
|
||||
define_num_seq(termination) // parallel only
|
||||
define_num_seq(parallel_other) // parallel only
|
||||
define_num_seq(mark_closure)
|
||||
define_num_seq(clear_ct) // parallel only
|
||||
define_num_seq(clear_ct)
|
||||
};
|
||||
|
||||
class Summary: public PauseSummary,
|
||||
@ -115,7 +115,6 @@ private:
|
||||
double _cur_collection_par_time_ms;
|
||||
double _cur_satb_drain_time_ms;
|
||||
double _cur_clear_ct_time_ms;
|
||||
bool _satb_drain_time_set;
|
||||
double _cur_ref_proc_time_ms;
|
||||
double _cur_ref_enq_time_ms;
|
||||
|
||||
@ -176,6 +175,11 @@ private:
|
||||
double* _par_last_gc_worker_end_times_ms;
|
||||
double* _par_last_gc_worker_times_ms;
|
||||
|
||||
// Each workers 'other' time i.e. the elapsed time of the parallel
|
||||
// phase of the pause minus the sum of the individual sub-phase
|
||||
// times for a given worker thread.
|
||||
double* _par_last_gc_worker_other_times_ms;
|
||||
|
||||
// indicates whether we are in full young or partially young GC mode
|
||||
bool _full_young_gcs;
|
||||
|
||||
@ -892,11 +896,12 @@ public:
|
||||
}
|
||||
|
||||
void record_satb_drain_time(double ms) {
|
||||
assert(_g1->mark_in_progress(), "shouldn't be here otherwise");
|
||||
_cur_satb_drain_time_ms = ms;
|
||||
_satb_drain_time_set = true;
|
||||
}
|
||||
|
||||
void record_satb_drain_processed_buffers (int processed_buffers) {
|
||||
void record_satb_drain_processed_buffers(int processed_buffers) {
|
||||
assert(_g1->mark_in_progress(), "shouldn't be here otherwise");
|
||||
_last_satb_drain_processed_buffers = processed_buffers;
|
||||
}
|
||||
|
||||
|
@ -122,10 +122,10 @@ public:
|
||||
void set_try_claimed() { _try_claimed = true; }
|
||||
|
||||
void scanCard(size_t index, HeapRegion *r) {
|
||||
DirtyCardToOopClosure* cl =
|
||||
r->new_dcto_closure(_oc,
|
||||
CardTableModRefBS::Precise,
|
||||
HeapRegionDCTOC::IntoCSFilterKind);
|
||||
// Stack allocate the DirtyCardToOopClosure instance
|
||||
HeapRegionDCTOC cl(_g1h, r, _oc,
|
||||
CardTableModRefBS::Precise,
|
||||
HeapRegionDCTOC::IntoCSFilterKind);
|
||||
|
||||
// Set the "from" region in the closure.
|
||||
_oc->set_region(r);
|
||||
@ -140,7 +140,7 @@ public:
|
||||
// scans (the rsets of the regions in the cset can intersect).
|
||||
_ct_bs->set_card_claimed(index);
|
||||
_cards_done++;
|
||||
cl->do_MemRegion(mr);
|
||||
cl.do_MemRegion(mr);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -340,14 +340,6 @@ void HeapRegion::reset_after_compaction() {
|
||||
init_top_at_mark_start();
|
||||
}
|
||||
|
||||
DirtyCardToOopClosure*
|
||||
HeapRegion::new_dcto_closure(OopClosure* cl,
|
||||
CardTableModRefBS::PrecisionStyle precision,
|
||||
HeapRegionDCTOC::FilterKind fk) {
|
||||
return new HeapRegionDCTOC(G1CollectedHeap::heap(),
|
||||
this, cl, precision, fk);
|
||||
}
|
||||
|
||||
void HeapRegion::hr_clear(bool par, bool clear_space) {
|
||||
assert(_humongous_type == NotHumongous,
|
||||
"we should have already filtered out humongous regions");
|
||||
|
@ -431,6 +431,14 @@ class HeapRegion: public G1OffsetTableContigSpace {
|
||||
return _humongous_start_region;
|
||||
}
|
||||
|
||||
// Same as Space::is_in_reserved, but will use the original size of the region.
|
||||
// The original size is different only for start humongous regions. They get
|
||||
// their _end set up to be the end of the last continues region of the
|
||||
// corresponding humongous object.
|
||||
bool is_in_reserved_raw(const void* p) const {
|
||||
return _bottom <= p && p < _orig_end;
|
||||
}
|
||||
|
||||
// Makes the current region be a "starts humongous" region, i.e.,
|
||||
// the first region in a series of one or more contiguous regions
|
||||
// that will contain a single "humongous" object. The two parameters
|
||||
@ -569,11 +577,6 @@ class HeapRegion: public G1OffsetTableContigSpace {
|
||||
// allocated in the current region before the last call to "save_mark".
|
||||
void oop_before_save_marks_iterate(OopClosure* cl);
|
||||
|
||||
DirtyCardToOopClosure*
|
||||
new_dcto_closure(OopClosure* cl,
|
||||
CardTableModRefBS::PrecisionStyle precision,
|
||||
HeapRegionDCTOC::FilterKind fk);
|
||||
|
||||
// Note the start or end of marking. This tells the heap region
|
||||
// that the collector is about to start or has finished (concurrently)
|
||||
// marking the heap.
|
||||
|
@ -143,7 +143,11 @@ protected:
|
||||
// If the test below fails, then this table was reused concurrently
|
||||
// with this operation. This is OK, since the old table was coarsened,
|
||||
// and adding a bit to the new table is never incorrect.
|
||||
if (loc_hr->is_in_reserved(from)) {
|
||||
// If the table used to belong to a continues humongous region and is
|
||||
// now reused for the corresponding start humongous region, we need to
|
||||
// make sure that we detect this. Thus, we call is_in_reserved_raw()
|
||||
// instead of just is_in_reserved() here.
|
||||
if (loc_hr->is_in_reserved_raw(from)) {
|
||||
size_t hw_offset = pointer_delta((HeapWord*)from, loc_hr->bottom());
|
||||
CardIdx_t from_card = (CardIdx_t)
|
||||
hw_offset >> (CardTableModRefBS::card_shift - LogHeapWordSize);
|
||||
|
@ -23,6 +23,7 @@
|
||||
*/
|
||||
|
||||
#include "precompiled.hpp"
|
||||
#include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
|
||||
#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
|
||||
#include "gc_implementation/g1/g1CollectorPolicy.hpp"
|
||||
#include "gc_implementation/g1/vm_operations_g1.hpp"
|
||||
@ -165,6 +166,20 @@ void VM_G1IncCollectionPause::doit_epilogue() {
|
||||
}
|
||||
}
|
||||
|
||||
void VM_CGC_Operation::acquire_pending_list_lock() {
|
||||
// The caller may block while communicating
|
||||
// with the SLT thread in order to acquire/release the PLL.
|
||||
ConcurrentMarkThread::slt()->
|
||||
manipulatePLL(SurrogateLockerThread::acquirePLL);
|
||||
}
|
||||
|
||||
void VM_CGC_Operation::release_and_notify_pending_list_lock() {
|
||||
// The caller may block while communicating
|
||||
// with the SLT thread in order to acquire/release the PLL.
|
||||
ConcurrentMarkThread::slt()->
|
||||
manipulatePLL(SurrogateLockerThread::releaseAndNotifyPLL);
|
||||
}
|
||||
|
||||
void VM_CGC_Operation::doit() {
|
||||
gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
|
||||
TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
|
||||
@ -180,12 +195,19 @@ void VM_CGC_Operation::doit() {
|
||||
}
|
||||
|
||||
bool VM_CGC_Operation::doit_prologue() {
|
||||
// Note the relative order of the locks must match that in
|
||||
// VM_GC_Operation::doit_prologue() or deadlocks can occur
|
||||
acquire_pending_list_lock();
|
||||
|
||||
Heap_lock->lock();
|
||||
SharedHeap::heap()->_thread_holds_heap_lock_for_gc = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void VM_CGC_Operation::doit_epilogue() {
|
||||
// Note the relative order of the unlocks must match that in
|
||||
// VM_GC_Operation::doit_epilogue()
|
||||
SharedHeap::heap()->_thread_holds_heap_lock_for_gc = false;
|
||||
Heap_lock->unlock();
|
||||
release_and_notify_pending_list_lock();
|
||||
}
|
||||
|
@ -93,11 +93,17 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
// Concurrent GC stop-the-world operations such as initial and final mark;
|
||||
// Concurrent GC stop-the-world operations such as remark and cleanup;
|
||||
// consider sharing these with CMS's counterparts.
|
||||
class VM_CGC_Operation: public VM_Operation {
|
||||
VoidClosure* _cl;
|
||||
const char* _printGCMessage;
|
||||
|
||||
protected:
|
||||
// java.lang.ref.Reference support
|
||||
void acquire_pending_list_lock();
|
||||
void release_and_notify_pending_list_lock();
|
||||
|
||||
public:
|
||||
VM_CGC_Operation(VoidClosure* cl, const char *printGCMsg)
|
||||
: _cl(cl), _printGCMessage(printGCMsg) { }
|
||||
|
@ -224,6 +224,8 @@ void SurrogateLockerThread::manipulatePLL(SLT_msg_type msg) {
|
||||
MutexLockerEx x(&_monitor, Mutex::_no_safepoint_check_flag);
|
||||
assert(_buffer == empty, "Should be empty");
|
||||
assert(msg != empty, "empty message");
|
||||
assert(!Heap_lock->owned_by_self(), "Heap_lock owned by requesting thread");
|
||||
|
||||
_buffer = msg;
|
||||
while (_buffer != empty) {
|
||||
_monitor.notify();
|
||||
|
@ -132,3 +132,4 @@ c114306576dcc1cb871a48058b41bf7d87ce882a jdk8-b07
|
||||
de4794dd69c48b08029d158a972993ff9d5627df jdk8-b08
|
||||
93554324c014282571aeeb48552ad00d3fedb089 jdk8-b09
|
||||
d21a4d5141c04bc9e88f2c0253121d449b66d667 jdk8-b10
|
||||
d1b7a4f6dd2065fdeafbcdfd9dcc0072da8c6881 jdk8-b11
|
||||
|
@ -132,3 +132,4 @@ acffff22a9465005e8eb206224fae9f2ea4fd469 jdk8-b06
|
||||
1c9d4f59acf8f71477473c170239b43b2c9dee24 jdk8-b08
|
||||
70172e57cf29efe271b068987eefb601c2a77780 jdk8-b09
|
||||
8e7fdc8e3c758644ca6d0fd70bb255e9d2e64cda jdk8-b10
|
||||
a12ab897a249feb7859a6e6cd84b49411f4c06ac jdk8-b11
|
||||
|
@ -132,3 +132,5 @@ bdb870cc269ef8b221d17a217be89092400b59d2 jdk8-b06
|
||||
1c023bcd0c5a01ac07bc7eea728aafbb0d8991e9 jdk8-b08
|
||||
f1ec21b8142168ff40f3278d2f6b5fe4bd5f3b26 jdk8-b09
|
||||
4788745572ef2bde34924ef34e7e4d55ba07e979 jdk8-b10
|
||||
7ab0d613cd1a271a9763ffb894dc1f0a5b95a7e4 jdk8-b11
|
||||
09fd2067f715e4505c44b01c301258a4e8f8964e jdk8-b12
|
||||
|
@ -189,7 +189,7 @@ public class UnixPrintServiceLookup extends PrintServiceLookup
|
||||
if (printServices == null) {
|
||||
return new PrintService[0];
|
||||
} else {
|
||||
return printServices;
|
||||
return (PrintService[])printServices.clone();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -486,7 +486,7 @@ public class D3DSurfaceData extends SurfaceData implements AccelSurface {
|
||||
int dataType = 0;
|
||||
int scanStride = width;
|
||||
|
||||
if (dcm.getPixelSize() == 24 || dcm.getPixelSize() == 32) {
|
||||
if (dcm.getPixelSize() > 16) {
|
||||
dataType = DataBuffer.TYPE_INT;
|
||||
} else {
|
||||
// 15, 16
|
||||
|
104
jdk/test/sun/java2d/DirectX/DrawBitmaskToSurfaceTest.java
Normal file
104
jdk/test/sun/java2d/DirectX/DrawBitmaskToSurfaceTest.java
Normal file
@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 6997116
|
||||
* @summary Test verifies that rendering of images with bitmap transparency
|
||||
* to a D3D surface does not cause an ClassCastException.
|
||||
*
|
||||
* @run main/othervm -Dsun.java2d.d3d=True DrawBitmaskToSurfaceTest
|
||||
*/
|
||||
|
||||
import java.awt.Graphics;
|
||||
import java.awt.Image;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.IndexColorModel;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import javax.swing.JFrame;
|
||||
|
||||
public class DrawBitmaskToSurfaceTest extends JFrame {
|
||||
|
||||
private final Image src;
|
||||
private static java.util.concurrent.CountDownLatch latch = null;
|
||||
private static Throwable theError = null;
|
||||
|
||||
public DrawBitmaskToSurfaceTest() {
|
||||
src = createTestImage();
|
||||
}
|
||||
|
||||
private static Image createTestImage() {
|
||||
byte[] r = new byte[]{(byte)0x00, (byte)0x80, (byte)0xff, (byte)0xff};
|
||||
byte[] g = new byte[]{(byte)0x00, (byte)0x80, (byte)0xff, (byte)0x00};
|
||||
byte[] b = new byte[]{(byte)0x00, (byte)0x80, (byte)0xff, (byte)0x00};
|
||||
|
||||
IndexColorModel icm = new IndexColorModel(2, 4, r, g, b, 3);
|
||||
|
||||
BufferedImage img = new BufferedImage(100, 100,
|
||||
BufferedImage.TYPE_BYTE_INDEXED,
|
||||
icm);
|
||||
return img;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void paint(final Graphics g) {
|
||||
try {
|
||||
System.err.println("paint frame....");
|
||||
g.drawImage(src, 30, 30, this);
|
||||
} catch (Throwable e) {
|
||||
theError = e;
|
||||
} finally {
|
||||
if (latch != null) {
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(final String[] args) throws Exception {
|
||||
final JFrame frame = new DrawBitmaskToSurfaceTest();
|
||||
frame.setBounds(10, 350, 200, 200);
|
||||
frame.setVisible(true);
|
||||
|
||||
Thread.sleep(2000);
|
||||
|
||||
System.err.println("Change frame bounds...");
|
||||
latch = new CountDownLatch(1);
|
||||
frame.setBounds(10, 350, 90, 90);
|
||||
frame.repaint();
|
||||
|
||||
try {
|
||||
if (latch.getCount() > 0) {
|
||||
latch.await();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
|
||||
frame.dispose();
|
||||
|
||||
if (theError != null) {
|
||||
throw new RuntimeException("Test failed.", theError);
|
||||
}
|
||||
|
||||
System.err.println("Test passed");
|
||||
}
|
||||
}
|
@ -132,3 +132,4 @@ d2422276f9dabc848b7a079025719826d2f9a30f jdk8-b06
|
||||
e8acc2d6c32f0c8321e642e1a86672a2e196a056 jdk8-b08
|
||||
b7a7e47c8d3daf7822abf7c37e5179ccbbf53008 jdk8-b09
|
||||
f6c783e18bdf4d46a0ab273868afebbf32600ff7 jdk8-b10
|
||||
4bf01f1c4e3464f378959d10f3983a0469181d94 jdk8-b11
|
||||
|
@ -42,7 +42,6 @@ import com.sun.tools.javac.tree.JCTree.*;
|
||||
import com.sun.tools.apt.comp.*;
|
||||
import com.sun.tools.apt.util.Bark;
|
||||
import com.sun.mirror.apt.AnnotationProcessorFactory;
|
||||
import com.sun.tools.javac.parser.DocCommentScanner;
|
||||
|
||||
/**
|
||||
* <p><b>This is NOT part of any supported API.
|
||||
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
|
||||
* Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
@ -56,7 +56,7 @@ import com.sun.tools.apt.comp.UsageMessageNeededException;
|
||||
import com.sun.tools.apt.util.Bark;
|
||||
import com.sun.mirror.apt.AnnotationProcessorFactory;
|
||||
|
||||
import static com.sun.tools.javac.file.Paths.pathToURLs;
|
||||
import static com.sun.tools.javac.file.Locations.pathToURLs;
|
||||
|
||||
/** This class provides a commandline interface to the apt build-time
|
||||
* tool.
|
||||
|
@ -258,7 +258,7 @@ public abstract class Printer implements Type.Visitor<String, Locale>, Symbol.Vi
|
||||
ClassType norm = (ClassType) t.tsym.type;
|
||||
if (norm == null) {
|
||||
s = localize(locale, "compiler.misc.anonymous.class", (Object) null);
|
||||
} else if (norm.interfaces_field.nonEmpty()) {
|
||||
} else if (norm.interfaces_field != null && norm.interfaces_field.nonEmpty()) {
|
||||
s = localize(locale, "compiler.misc.anonymous.class",
|
||||
visit(norm.interfaces_field.head, locale));
|
||||
} else {
|
||||
|
@ -278,7 +278,6 @@ public class Types {
|
||||
boolean tPrimitive = t.isPrimitive();
|
||||
boolean sPrimitive = s.isPrimitive();
|
||||
if (tPrimitive == sPrimitive) {
|
||||
checkUnsafeVarargsConversion(t, s, warn);
|
||||
return isSubtypeUnchecked(t, s, warn);
|
||||
}
|
||||
if (!allowBoxing) return false;
|
||||
@ -286,27 +285,6 @@ public class Types {
|
||||
? isSubtype(boxedClass(t).type, s)
|
||||
: isSubtype(unboxedType(t), s);
|
||||
}
|
||||
//where
|
||||
private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
|
||||
if (t.tag != ARRAY || isReifiable(t)) return;
|
||||
ArrayType from = (ArrayType)t;
|
||||
boolean shouldWarn = false;
|
||||
switch (s.tag) {
|
||||
case ARRAY:
|
||||
ArrayType to = (ArrayType)s;
|
||||
shouldWarn = from.isVarargs() &&
|
||||
!to.isVarargs() &&
|
||||
!isReifiable(from);
|
||||
break;
|
||||
case CLASS:
|
||||
shouldWarn = from.isVarargs() &&
|
||||
isSubtype(from, s);
|
||||
break;
|
||||
}
|
||||
if (shouldWarn) {
|
||||
warn.warn(LintCategory.VARARGS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Is t a subtype of or convertiable via boxing/unboxing
|
||||
@ -328,42 +306,63 @@ public class Types {
|
||||
* Is t an unchecked subtype of s?
|
||||
*/
|
||||
public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
|
||||
if (t.tag == ARRAY && s.tag == ARRAY) {
|
||||
if (((ArrayType)t).elemtype.tag <= lastBaseTag) {
|
||||
return isSameType(elemtype(t), elemtype(s));
|
||||
} else {
|
||||
ArrayType from = (ArrayType)t;
|
||||
ArrayType to = (ArrayType)s;
|
||||
if (from.isVarargs() &&
|
||||
!to.isVarargs() &&
|
||||
!isReifiable(from)) {
|
||||
warn.warn(LintCategory.VARARGS);
|
||||
boolean result = isSubtypeUncheckedInternal(t, s, warn);
|
||||
if (result) {
|
||||
checkUnsafeVarargsConversion(t, s, warn);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
//where
|
||||
private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
|
||||
if (t.tag == ARRAY && s.tag == ARRAY) {
|
||||
if (((ArrayType)t).elemtype.tag <= lastBaseTag) {
|
||||
return isSameType(elemtype(t), elemtype(s));
|
||||
} else {
|
||||
return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
|
||||
}
|
||||
return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
|
||||
}
|
||||
} else if (isSubtype(t, s)) {
|
||||
return true;
|
||||
}
|
||||
else if (t.tag == TYPEVAR) {
|
||||
return isSubtypeUnchecked(t.getUpperBound(), s, warn);
|
||||
}
|
||||
else if (s.tag == UNDETVAR) {
|
||||
UndetVar uv = (UndetVar)s;
|
||||
if (uv.inst != null)
|
||||
return isSubtypeUnchecked(t, uv.inst, warn);
|
||||
}
|
||||
else if (!s.isRaw()) {
|
||||
Type t2 = asSuper(t, s.tsym);
|
||||
if (t2 != null && t2.isRaw()) {
|
||||
if (isReifiable(s))
|
||||
warn.silentWarn(LintCategory.UNCHECKED);
|
||||
else
|
||||
warn.warn(LintCategory.UNCHECKED);
|
||||
} else if (isSubtype(t, s)) {
|
||||
return true;
|
||||
}
|
||||
else if (t.tag == TYPEVAR) {
|
||||
return isSubtypeUnchecked(t.getUpperBound(), s, warn);
|
||||
}
|
||||
else if (s.tag == UNDETVAR) {
|
||||
UndetVar uv = (UndetVar)s;
|
||||
if (uv.inst != null)
|
||||
return isSubtypeUnchecked(t, uv.inst, warn);
|
||||
}
|
||||
else if (!s.isRaw()) {
|
||||
Type t2 = asSuper(t, s.tsym);
|
||||
if (t2 != null && t2.isRaw()) {
|
||||
if (isReifiable(s))
|
||||
warn.silentWarn(LintCategory.UNCHECKED);
|
||||
else
|
||||
warn.warn(LintCategory.UNCHECKED);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
|
||||
if (t.tag != ARRAY || isReifiable(t)) return;
|
||||
ArrayType from = (ArrayType)t;
|
||||
boolean shouldWarn = false;
|
||||
switch (s.tag) {
|
||||
case ARRAY:
|
||||
ArrayType to = (ArrayType)s;
|
||||
shouldWarn = from.isVarargs() &&
|
||||
!to.isVarargs() &&
|
||||
!isReifiable(from);
|
||||
break;
|
||||
case CLASS:
|
||||
shouldWarn = from.isVarargs();
|
||||
break;
|
||||
}
|
||||
if (shouldWarn) {
|
||||
warn.warn(LintCategory.VARARGS);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is t a subtype of s?<br>
|
||||
|
@ -34,7 +34,8 @@ import com.sun.tools.javac.code.*;
|
||||
import com.sun.tools.javac.code.Type.*;
|
||||
import com.sun.tools.javac.code.Type.ForAll.ConstraintKind;
|
||||
import com.sun.tools.javac.code.Symbol.*;
|
||||
import com.sun.tools.javac.util.JCDiagnostic;
|
||||
import com.sun.tools.javac.comp.Resolve.VerboseResolutionMode;
|
||||
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
|
||||
|
||||
import static com.sun.tools.javac.code.TypeTags.*;
|
||||
|
||||
@ -56,6 +57,7 @@ public class Infer {
|
||||
Types types;
|
||||
Check chk;
|
||||
Resolve rs;
|
||||
Log log;
|
||||
JCDiagnostic.Factory diags;
|
||||
|
||||
public static Infer instance(Context context) {
|
||||
@ -70,6 +72,7 @@ public class Infer {
|
||||
syms = Symtab.instance(context);
|
||||
types = Types.instance(context);
|
||||
rs = Resolve.instance(context);
|
||||
log = Log.instance(context);
|
||||
chk = Check.instance(context);
|
||||
diags = JCDiagnostic.Factory.instance(context);
|
||||
ambiguousNoInstanceException =
|
||||
@ -460,7 +463,7 @@ public class Infer {
|
||||
// quantify result type with them
|
||||
final List<Type> inferredTypes = insttypes.toList();
|
||||
final List<Type> all_tvars = tvars; //this is the wrong tvars
|
||||
return new UninferredMethodType(mt, restvars.toList()) {
|
||||
return new UninferredMethodType(env.tree.pos(), msym, mt, restvars.toList()) {
|
||||
@Override
|
||||
List<Type> getConstraints(TypeVar tv, ConstraintKind ck) {
|
||||
for (Type t : restundet.toList()) {
|
||||
@ -502,13 +505,17 @@ public class Infer {
|
||||
* type - when the return type is instantiated (see Infer.instantiateExpr)
|
||||
* the underlying method type is also updated.
|
||||
*/
|
||||
static abstract class UninferredMethodType extends DelegatedType {
|
||||
abstract class UninferredMethodType extends DelegatedType {
|
||||
|
||||
final List<Type> tvars;
|
||||
final Symbol msym;
|
||||
final DiagnosticPosition pos;
|
||||
|
||||
public UninferredMethodType(MethodType mtype, List<Type> tvars) {
|
||||
public UninferredMethodType(DiagnosticPosition pos, Symbol msym, MethodType mtype, List<Type> tvars) {
|
||||
super(METHOD, new MethodType(mtype.argtypes, null, mtype.thrown, mtype.tsym));
|
||||
this.tvars = tvars;
|
||||
this.msym = msym;
|
||||
this.pos = pos;
|
||||
asMethodType().restype = new UninferredReturnType(tvars, mtype.restype);
|
||||
}
|
||||
|
||||
@ -543,6 +550,9 @@ public class Infer {
|
||||
public Type inst(List<Type> actuals, Types types) {
|
||||
Type newRestype = super.inst(actuals, types);
|
||||
instantiateReturnType(newRestype, actuals, types);
|
||||
if (rs.verboseResolutionMode.contains(VerboseResolutionMode.DEFERRED_INST)) {
|
||||
log.note(pos, "deferred.method.inst", msym, UninferredMethodType.this.qtype, newRestype);
|
||||
}
|
||||
return newRestype;
|
||||
}
|
||||
@Override
|
||||
|
@ -25,29 +25,33 @@
|
||||
|
||||
package com.sun.tools.javac.comp;
|
||||
|
||||
import com.sun.tools.javac.util.*;
|
||||
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
|
||||
import com.sun.tools.javac.code.*;
|
||||
import com.sun.tools.javac.jvm.*;
|
||||
import com.sun.tools.javac.tree.*;
|
||||
import com.sun.tools.javac.api.Formattable.LocalizedString;
|
||||
import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
|
||||
|
||||
import com.sun.tools.javac.code.*;
|
||||
import com.sun.tools.javac.code.Type.*;
|
||||
import com.sun.tools.javac.code.Symbol.*;
|
||||
import com.sun.tools.javac.jvm.*;
|
||||
import com.sun.tools.javac.tree.*;
|
||||
import com.sun.tools.javac.tree.JCTree.*;
|
||||
import com.sun.tools.javac.util.*;
|
||||
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
|
||||
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
|
||||
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.lang.model.element.ElementVisitor;
|
||||
|
||||
import static com.sun.tools.javac.code.Flags.*;
|
||||
import static com.sun.tools.javac.code.Kinds.*;
|
||||
import static com.sun.tools.javac.code.TypeTags.*;
|
||||
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
|
||||
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
|
||||
import javax.lang.model.element.ElementVisitor;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
|
||||
|
||||
/** Helper class for name resolution, used mostly by the attribution phase.
|
||||
*
|
||||
@ -73,9 +77,45 @@ public class Resolve {
|
||||
public final boolean varargsEnabled; // = source.allowVarargs();
|
||||
public final boolean allowMethodHandles;
|
||||
private final boolean debugResolve;
|
||||
final EnumSet<VerboseResolutionMode> verboseResolutionMode;
|
||||
|
||||
Scope polymorphicSignatureScope;
|
||||
|
||||
enum VerboseResolutionMode {
|
||||
SUCCESS("success"),
|
||||
FAILURE("failure"),
|
||||
APPLICABLE("applicable"),
|
||||
INAPPLICABLE("inapplicable"),
|
||||
DEFERRED_INST("deferred-inference"),
|
||||
PREDEF("predef"),
|
||||
OBJECT_INIT("object-init"),
|
||||
INTERNAL("internal");
|
||||
|
||||
String opt;
|
||||
|
||||
private VerboseResolutionMode(String opt) {
|
||||
this.opt = opt;
|
||||
}
|
||||
|
||||
static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
|
||||
String s = opts.get("verboseResolution");
|
||||
EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
|
||||
if (s == null) return res;
|
||||
if (s.contains("all")) {
|
||||
res = EnumSet.allOf(VerboseResolutionMode.class);
|
||||
}
|
||||
Collection<String> args = Arrays.asList(s.split(","));
|
||||
for (VerboseResolutionMode mode : values()) {
|
||||
if (args.contains(mode.opt)) {
|
||||
res.add(mode);
|
||||
} else if (args.contains("-" + mode.opt)) {
|
||||
res.remove(mode);
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
public static Resolve instance(Context context) {
|
||||
Resolve instance = context.get(resolveKey);
|
||||
if (instance == null)
|
||||
@ -111,6 +151,7 @@ public class Resolve {
|
||||
varargsEnabled = source.allowVarargs();
|
||||
Options options = Options.instance(context);
|
||||
debugResolve = options.isSet("debugresolve");
|
||||
verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
|
||||
Target target = Target.instance(context);
|
||||
allowMethodHandles = target.hasMethodHandles();
|
||||
polymorphicSignatureScope = new Scope(syms.noSymbol);
|
||||
@ -684,13 +725,16 @@ public class Resolve {
|
||||
if (!sym.isInheritedIn(site.tsym, types)) return bestSoFar;
|
||||
Assert.check(sym.kind < AMBIGUOUS);
|
||||
try {
|
||||
rawInstantiate(env, site, sym, argtypes, typeargtypes,
|
||||
Type mt = rawInstantiate(env, site, sym, argtypes, typeargtypes,
|
||||
allowBoxing, useVarargs, Warner.noWarnings);
|
||||
if (!operator) addVerboseApplicableCandidateDiag(sym ,mt);
|
||||
} catch (InapplicableMethodException ex) {
|
||||
if (!operator) addVerboseInapplicableCandidateDiag(sym, ex.getDiagnostic());
|
||||
switch (bestSoFar.kind) {
|
||||
case ABSENT_MTH:
|
||||
return wrongMethod.setWrongSym(sym, ex.getDiagnostic());
|
||||
case WRONG_MTH:
|
||||
if (operator) return bestSoFar;
|
||||
wrongMethods.addCandidate(currentStep, wrongMethod.sym, wrongMethod.explanation);
|
||||
case WRONG_MTHS:
|
||||
return wrongMethods.addCandidate(currentStep, sym, ex.getDiagnostic());
|
||||
@ -708,6 +752,34 @@ public class Resolve {
|
||||
: mostSpecific(sym, bestSoFar, env, site,
|
||||
allowBoxing && operator, useVarargs);
|
||||
}
|
||||
//where
|
||||
void addVerboseApplicableCandidateDiag(Symbol sym, Type inst) {
|
||||
if (!verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE))
|
||||
return;
|
||||
|
||||
JCDiagnostic subDiag = null;
|
||||
if (inst.getReturnType().tag == FORALL) {
|
||||
Type diagType = types.createMethodTypeWithReturn(inst.asMethodType(),
|
||||
((ForAll)inst.getReturnType()).qtype);
|
||||
subDiag = diags.fragment("partial.inst.sig", diagType);
|
||||
} else if (sym.type.tag == FORALL) {
|
||||
subDiag = diags.fragment("full.inst.sig", inst.asMethodType());
|
||||
}
|
||||
|
||||
String key = subDiag == null ?
|
||||
"applicable.method.found" :
|
||||
"applicable.method.found.1";
|
||||
|
||||
verboseResolutionCandidateDiags.put(sym,
|
||||
diags.fragment(key, verboseResolutionCandidateDiags.size(), sym, subDiag));
|
||||
}
|
||||
|
||||
void addVerboseInapplicableCandidateDiag(Symbol sym, JCDiagnostic subDiag) {
|
||||
if (!verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))
|
||||
return;
|
||||
verboseResolutionCandidateDiags.put(sym,
|
||||
diags.fragment("not.applicable.method.found", verboseResolutionCandidateDiags.size(), sym, subDiag));
|
||||
}
|
||||
|
||||
/* Return the most specific of the two methods for a call,
|
||||
* given that both are accessible and applicable.
|
||||
@ -905,8 +977,9 @@ public class Resolve {
|
||||
boolean allowBoxing,
|
||||
boolean useVarargs,
|
||||
boolean operator) {
|
||||
verboseResolutionCandidateDiags.clear();
|
||||
Symbol bestSoFar = methodNotFound;
|
||||
return findMethod(env,
|
||||
bestSoFar = findMethod(env,
|
||||
site,
|
||||
name,
|
||||
argtypes,
|
||||
@ -918,6 +991,8 @@ public class Resolve {
|
||||
useVarargs,
|
||||
operator,
|
||||
new HashSet<TypeSymbol>());
|
||||
reportVerboseResolutionDiagnostic(env.tree.pos(), name, site, argtypes, typeargtypes, bestSoFar);
|
||||
return bestSoFar;
|
||||
}
|
||||
// where
|
||||
private Symbol findMethod(Env<AttrContext> env,
|
||||
@ -975,6 +1050,37 @@ public class Resolve {
|
||||
}
|
||||
return bestSoFar;
|
||||
}
|
||||
//where
|
||||
void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site, List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
|
||||
boolean success = bestSoFar.kind < ERRONEOUS;
|
||||
|
||||
if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
|
||||
return;
|
||||
} else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (bestSoFar.name == names.init &&
|
||||
bestSoFar.owner == syms.objectType.tsym &&
|
||||
!verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
|
||||
return; //skip diags for Object constructor resolution
|
||||
} else if (site == syms.predefClass.type && !verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
|
||||
return; //skip spurious diags for predef symbols (i.e. operators)
|
||||
} else if (internalResolution && !verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
|
||||
return;
|
||||
}
|
||||
|
||||
int pos = 0;
|
||||
for (Symbol s : verboseResolutionCandidateDiags.keySet()) {
|
||||
if (s == bestSoFar) break;
|
||||
pos++;
|
||||
}
|
||||
String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
|
||||
JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name, site.tsym, pos, currentStep,
|
||||
methodArguments(argtypes), methodArguments(typeargtypes));
|
||||
JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, List.from(verboseResolutionCandidateDiags.values().toArray(new JCDiagnostic[verboseResolutionCandidateDiags.size()])));
|
||||
log.report(d);
|
||||
}
|
||||
|
||||
/** Find unqualified method matching given name, type and value arguments.
|
||||
* @param env The current environment.
|
||||
@ -1543,12 +1649,19 @@ public class Resolve {
|
||||
Type site, Name name,
|
||||
List<Type> argtypes,
|
||||
List<Type> typeargtypes) {
|
||||
Symbol sym = resolveQualifiedMethod(
|
||||
pos, env, site.tsym, site, name, argtypes, typeargtypes);
|
||||
if (sym.kind == MTH) return (MethodSymbol)sym;
|
||||
else throw new FatalError(
|
||||
diags.fragment("fatal.err.cant.locate.meth",
|
||||
name));
|
||||
boolean prevInternal = internalResolution;
|
||||
try {
|
||||
internalResolution = true;
|
||||
Symbol sym = resolveQualifiedMethod(
|
||||
pos, env, site.tsym, site, name, argtypes, typeargtypes);
|
||||
if (sym.kind == MTH) return (MethodSymbol)sym;
|
||||
else throw new FatalError(
|
||||
diags.fragment("fatal.err.cant.locate.meth",
|
||||
name));
|
||||
}
|
||||
finally {
|
||||
internalResolution = prevInternal;
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve constructor.
|
||||
@ -1685,6 +1798,7 @@ public class Resolve {
|
||||
*/
|
||||
Symbol resolveOperator(DiagnosticPosition pos, int optag,
|
||||
Env<AttrContext> env, List<Type> argtypes) {
|
||||
startResolution();
|
||||
Name name = treeinfo.operatorName(optag);
|
||||
Symbol sym = findMethod(env, syms.predefClass.type, name, argtypes,
|
||||
null, false, false, true);
|
||||
@ -1828,7 +1942,7 @@ public class Resolve {
|
||||
private final LocalizedString noArgs = new LocalizedString("compiler.misc.no.args");
|
||||
|
||||
public Object methodArguments(List<Type> argtypes) {
|
||||
return argtypes.isEmpty() ? noArgs : argtypes;
|
||||
return argtypes == null || argtypes.isEmpty() ? noArgs : argtypes;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -2375,10 +2489,15 @@ public class Resolve {
|
||||
private Map<MethodResolutionPhase, Symbol> methodResolutionCache =
|
||||
new HashMap<MethodResolutionPhase, Symbol>(MethodResolutionPhase.values().length);
|
||||
|
||||
private Map<Symbol, JCDiagnostic> verboseResolutionCandidateDiags =
|
||||
new LinkedHashMap<Symbol, JCDiagnostic>();
|
||||
|
||||
final List<MethodResolutionPhase> methodResolutionSteps = List.of(BASIC, BOX, VARARITY);
|
||||
|
||||
private MethodResolutionPhase currentStep = null;
|
||||
|
||||
private boolean internalResolution = false;
|
||||
|
||||
private MethodResolutionPhase firstErroneousResolutionPhase() {
|
||||
MethodResolutionPhase bestSoFar = BASIC;
|
||||
Symbol sym = methodNotFound;
|
||||
|
@ -25,7 +25,6 @@
|
||||
|
||||
package com.sun.tools.javac.file;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
@ -41,6 +40,7 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
@ -56,14 +56,12 @@ import javax.tools.StandardJavaFileManager;
|
||||
|
||||
import com.sun.tools.javac.file.RelativePath.RelativeFile;
|
||||
import com.sun.tools.javac.file.RelativePath.RelativeDirectory;
|
||||
import com.sun.tools.javac.main.OptionName;
|
||||
import com.sun.tools.javac.util.BaseFileManager;
|
||||
import com.sun.tools.javac.util.Context;
|
||||
import com.sun.tools.javac.util.List;
|
||||
import com.sun.tools.javac.util.ListBuffer;
|
||||
|
||||
import static javax.tools.StandardLocation.*;
|
||||
import static com.sun.tools.javac.main.OptionName.*;
|
||||
|
||||
/**
|
||||
* This class provides access to the source, class and other files
|
||||
@ -83,32 +81,14 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
|
||||
return buffer.toString().toCharArray();
|
||||
}
|
||||
|
||||
/** Encapsulates knowledge of paths
|
||||
*/
|
||||
private Paths paths;
|
||||
|
||||
private FSInfo fsInfo;
|
||||
|
||||
private boolean contextUseOptimizedZip;
|
||||
private ZipFileIndexCache zipFileIndexCache;
|
||||
|
||||
private final File uninited = new File("U N I N I T E D");
|
||||
|
||||
private final Set<JavaFileObject.Kind> sourceOrClass =
|
||||
EnumSet.of(JavaFileObject.Kind.SOURCE, JavaFileObject.Kind.CLASS);
|
||||
|
||||
/** The standard output directory, primarily used for classes.
|
||||
* Initialized by the "-d" option.
|
||||
* If classOutDir = null, files are written into same directory as the sources
|
||||
* they were generated from.
|
||||
*/
|
||||
private File classOutDir = uninited;
|
||||
|
||||
/** The output directory, used when generating sources while processing annotations.
|
||||
* Initialized by the "-s" option.
|
||||
*/
|
||||
private File sourceOutDir = uninited;
|
||||
|
||||
protected boolean mmappedIO;
|
||||
protected boolean ignoreSymbolFile;
|
||||
|
||||
@ -154,13 +134,6 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
|
||||
@Override
|
||||
public void setContext(Context context) {
|
||||
super.setContext(context);
|
||||
if (paths == null) {
|
||||
paths = Paths.instance(context);
|
||||
} else {
|
||||
// Reuse the Paths object as it stores the locations that
|
||||
// have been set with setLocation, etc.
|
||||
paths.setContext(context);
|
||||
}
|
||||
|
||||
fsInfo = FSInfo.instance(context);
|
||||
|
||||
@ -179,7 +152,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
|
||||
|
||||
@Override
|
||||
public boolean isDefaultBootClassPath() {
|
||||
return paths.isDefaultBootClassPath();
|
||||
return locations.isDefaultBootClassPath();
|
||||
}
|
||||
|
||||
public JavaFileObject getFileForInput(String name) {
|
||||
@ -493,7 +466,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
|
||||
*/
|
||||
private Archive openArchive(File zipFileName, boolean useOptimizedZip) throws IOException {
|
||||
File origZipFileName = zipFileName;
|
||||
if (!ignoreSymbolFile && paths.isDefaultBootClassPathRtJar(zipFileName)) {
|
||||
if (!ignoreSymbolFile && locations.isDefaultBootClassPathRtJar(zipFileName)) {
|
||||
File file = zipFileName.getParentFile().getParentFile(); // ${java.home}
|
||||
if (new File(file.getName()).equals(new File("jre")))
|
||||
file = file.getParentFile();
|
||||
@ -780,7 +753,7 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
|
||||
} else if (location == SOURCE_OUTPUT) {
|
||||
dir = (getSourceOutDir() != null ? getSourceOutDir() : getClassOutDir());
|
||||
} else {
|
||||
Iterable<? extends File> path = paths.getPathForLocation(location);
|
||||
Iterable<? extends File> path = locations.getLocation(location);
|
||||
dir = null;
|
||||
for (File f: path) {
|
||||
dir = f;
|
||||
@ -815,64 +788,20 @@ public class JavacFileManager extends BaseFileManager implements StandardJavaFil
|
||||
throws IOException
|
||||
{
|
||||
nullCheck(location);
|
||||
paths.lazy();
|
||||
|
||||
final File dir = location.isOutputLocation() ? getOutputDirectory(path) : null;
|
||||
|
||||
if (location == CLASS_OUTPUT)
|
||||
classOutDir = getOutputLocation(dir, D);
|
||||
else if (location == SOURCE_OUTPUT)
|
||||
sourceOutDir = getOutputLocation(dir, S);
|
||||
else
|
||||
paths.setPathForLocation(location, path);
|
||||
}
|
||||
// where
|
||||
private File getOutputDirectory(Iterable<? extends File> path) throws IOException {
|
||||
if (path == null)
|
||||
return null;
|
||||
Iterator<? extends File> pathIter = path.iterator();
|
||||
if (!pathIter.hasNext())
|
||||
throw new IllegalArgumentException("empty path for directory");
|
||||
File dir = pathIter.next();
|
||||
if (pathIter.hasNext())
|
||||
throw new IllegalArgumentException("path too long for directory");
|
||||
if (!dir.exists())
|
||||
throw new FileNotFoundException(dir + ": does not exist");
|
||||
else if (!dir.isDirectory())
|
||||
throw new IOException(dir + ": not a directory");
|
||||
return dir;
|
||||
}
|
||||
|
||||
private File getOutputLocation(File dir, OptionName defaultOptionName) {
|
||||
if (dir != null)
|
||||
return dir;
|
||||
String arg = options.get(defaultOptionName);
|
||||
if (arg == null)
|
||||
return null;
|
||||
return new File(arg);
|
||||
locations.setLocation(location, path);
|
||||
}
|
||||
|
||||
public Iterable<? extends File> getLocation(Location location) {
|
||||
nullCheck(location);
|
||||
paths.lazy();
|
||||
if (location == CLASS_OUTPUT) {
|
||||
return (getClassOutDir() == null ? null : List.of(getClassOutDir()));
|
||||
} else if (location == SOURCE_OUTPUT) {
|
||||
return (getSourceOutDir() == null ? null : List.of(getSourceOutDir()));
|
||||
} else
|
||||
return paths.getPathForLocation(location);
|
||||
return locations.getLocation(location);
|
||||
}
|
||||
|
||||
private File getClassOutDir() {
|
||||
if (classOutDir == uninited)
|
||||
classOutDir = getOutputLocation(null, D);
|
||||
return classOutDir;
|
||||
return locations.getOutputLocation(CLASS_OUTPUT);
|
||||
}
|
||||
|
||||
private File getSourceOutDir() {
|
||||
if (sourceOutDir == uninited)
|
||||
sourceOutDir = getOutputLocation(null, S);
|
||||
return sourceOutDir;
|
||||
return locations.getOutputLocation(SOURCE_OUTPUT);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -0,0 +1,771 @@
|
||||
/*
|
||||
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package com.sun.tools.javac.file;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.Iterator;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.zip.ZipFile;
|
||||
import javax.tools.JavaFileManager.Location;
|
||||
import javax.tools.StandardLocation;
|
||||
|
||||
import com.sun.tools.javac.code.Lint;
|
||||
import com.sun.tools.javac.main.OptionName;
|
||||
import com.sun.tools.javac.util.ListBuffer;
|
||||
import com.sun.tools.javac.util.Log;
|
||||
import com.sun.tools.javac.util.Options;
|
||||
|
||||
import javax.tools.JavaFileManager;
|
||||
import static javax.tools.StandardLocation.*;
|
||||
import static com.sun.tools.javac.main.OptionName.*;
|
||||
|
||||
/** This class converts command line arguments, environment variables
|
||||
* and system properties (in File.pathSeparator-separated String form)
|
||||
* into a boot class path, user class path, and source path (in
|
||||
* Collection<String> form).
|
||||
*
|
||||
* <p><b>This is NOT part of any supported API.
|
||||
* If you write code that depends on this, you do so at your own risk.
|
||||
* This code and its internal interfaces are subject to change or
|
||||
* deletion without notice.</b>
|
||||
*/
|
||||
public class Locations {
|
||||
|
||||
/** The log to use for warning output */
|
||||
private Log log;
|
||||
|
||||
/** Collection of command-line options */
|
||||
private Options options;
|
||||
|
||||
/** Handler for -Xlint options */
|
||||
private Lint lint;
|
||||
|
||||
/** Access to (possibly cached) file info */
|
||||
private FSInfo fsInfo;
|
||||
|
||||
/** Whether to warn about non-existent path elements */
|
||||
private boolean warn;
|
||||
|
||||
// TODO: remove need for this
|
||||
private boolean inited = false; // TODO? caching bad?
|
||||
|
||||
public Locations() {
|
||||
initHandlers();
|
||||
}
|
||||
|
||||
public void update(Log log, Options options, Lint lint, FSInfo fsInfo) {
|
||||
this.log = log;
|
||||
this.options = options;
|
||||
this.lint = lint;
|
||||
this.fsInfo = fsInfo;
|
||||
}
|
||||
|
||||
public Collection<File> bootClassPath() {
|
||||
return getLocation(PLATFORM_CLASS_PATH);
|
||||
}
|
||||
|
||||
public boolean isDefaultBootClassPath() {
|
||||
BootClassPathLocationHandler h =
|
||||
(BootClassPathLocationHandler) getHandler(PLATFORM_CLASS_PATH);
|
||||
return h.isDefault();
|
||||
}
|
||||
|
||||
boolean isDefaultBootClassPathRtJar(File file) {
|
||||
BootClassPathLocationHandler h =
|
||||
(BootClassPathLocationHandler) getHandler(PLATFORM_CLASS_PATH);
|
||||
return h.isDefaultRtJar(file);
|
||||
}
|
||||
|
||||
public Collection<File> userClassPath() {
|
||||
return getLocation(CLASS_PATH);
|
||||
}
|
||||
|
||||
public Collection<File> sourcePath() {
|
||||
Collection<File> p = getLocation(SOURCE_PATH);
|
||||
// TODO: this should be handled by the LocationHandler
|
||||
return p == null || p.isEmpty() ? null : p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a path into its elements. Empty path elements will be ignored.
|
||||
* @param path The path to be split
|
||||
* @return The elements of the path
|
||||
*/
|
||||
private static Iterable<File> getPathEntries(String path) {
|
||||
return getPathEntries(path, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a path into its elements. If emptyPathDefault is not null, all
|
||||
* empty elements in the path, including empty elements at either end of
|
||||
* the path, will be replaced with the value of emptyPathDefault.
|
||||
* @param path The path to be split
|
||||
* @param emptyPathDefault The value to substitute for empty path elements,
|
||||
* or null, to ignore empty path elements
|
||||
* @return The elements of the path
|
||||
*/
|
||||
private static Iterable<File> getPathEntries(String path, File emptyPathDefault) {
|
||||
ListBuffer<File> entries = new ListBuffer<File>();
|
||||
int start = 0;
|
||||
while (start <= path.length()) {
|
||||
int sep = path.indexOf(File.pathSeparatorChar, start);
|
||||
if (sep == -1)
|
||||
sep = path.length();
|
||||
if (start < sep)
|
||||
entries.add(new File(path.substring(start, sep)));
|
||||
else if (emptyPathDefault != null)
|
||||
entries.add(emptyPathDefault);
|
||||
start = sep + 1;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility class to help evaluate a path option.
|
||||
* Duplicate entries are ignored, jar class paths can be expanded.
|
||||
*/
|
||||
private class Path extends LinkedHashSet<File> {
|
||||
private static final long serialVersionUID = 0;
|
||||
|
||||
private boolean expandJarClassPaths = false;
|
||||
private Set<File> canonicalValues = new HashSet<File>();
|
||||
|
||||
public Path expandJarClassPaths(boolean x) {
|
||||
expandJarClassPaths = x;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** What to use when path element is the empty string */
|
||||
private File emptyPathDefault = null;
|
||||
|
||||
public Path emptyPathDefault(File x) {
|
||||
emptyPathDefault = x;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Path() { super(); }
|
||||
|
||||
public Path addDirectories(String dirs, boolean warn) {
|
||||
boolean prev = expandJarClassPaths;
|
||||
expandJarClassPaths = true;
|
||||
try {
|
||||
if (dirs != null)
|
||||
for (File dir : getPathEntries(dirs))
|
||||
addDirectory(dir, warn);
|
||||
return this;
|
||||
} finally {
|
||||
expandJarClassPaths = prev;
|
||||
}
|
||||
}
|
||||
|
||||
public Path addDirectories(String dirs) {
|
||||
return addDirectories(dirs, warn);
|
||||
}
|
||||
|
||||
private void addDirectory(File dir, boolean warn) {
|
||||
if (!dir.isDirectory()) {
|
||||
if (warn)
|
||||
log.warning(Lint.LintCategory.PATH,
|
||||
"dir.path.element.not.found", dir);
|
||||
return;
|
||||
}
|
||||
|
||||
File[] files = dir.listFiles();
|
||||
if (files == null)
|
||||
return;
|
||||
|
||||
for (File direntry : files) {
|
||||
if (isArchive(direntry))
|
||||
addFile(direntry, warn);
|
||||
}
|
||||
}
|
||||
|
||||
public Path addFiles(String files, boolean warn) {
|
||||
if (files != null) {
|
||||
addFiles(getPathEntries(files, emptyPathDefault), warn);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Path addFiles(String files) {
|
||||
return addFiles(files, warn);
|
||||
}
|
||||
|
||||
public Path addFiles(Iterable<? extends File> files, boolean warn) {
|
||||
if (files != null) {
|
||||
for (File file: files)
|
||||
addFile(file, warn);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Path addFiles(Iterable<? extends File> files) {
|
||||
return addFiles(files, warn);
|
||||
}
|
||||
|
||||
public void addFile(File file, boolean warn) {
|
||||
if (contains(file)) {
|
||||
// discard duplicates
|
||||
return;
|
||||
}
|
||||
|
||||
if (! fsInfo.exists(file)) {
|
||||
/* No such file or directory exists */
|
||||
if (warn) {
|
||||
log.warning(Lint.LintCategory.PATH,
|
||||
"path.element.not.found", file);
|
||||
}
|
||||
super.add(file);
|
||||
return;
|
||||
}
|
||||
|
||||
File canonFile = fsInfo.getCanonicalFile(file);
|
||||
if (canonicalValues.contains(canonFile)) {
|
||||
/* Discard duplicates and avoid infinite recursion */
|
||||
return;
|
||||
}
|
||||
|
||||
if (fsInfo.isFile(file)) {
|
||||
/* File is an ordinary file. */
|
||||
if (!isArchive(file)) {
|
||||
/* Not a recognized extension; open it to see if
|
||||
it looks like a valid zip file. */
|
||||
try {
|
||||
ZipFile z = new ZipFile(file);
|
||||
z.close();
|
||||
if (warn) {
|
||||
log.warning(Lint.LintCategory.PATH,
|
||||
"unexpected.archive.file", file);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// FIXME: include e.getLocalizedMessage in warning
|
||||
if (warn) {
|
||||
log.warning(Lint.LintCategory.PATH,
|
||||
"invalid.archive.file", file);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Now what we have left is either a directory or a file name
|
||||
conforming to archive naming convention */
|
||||
super.add(file);
|
||||
canonicalValues.add(canonFile);
|
||||
|
||||
if (expandJarClassPaths && fsInfo.isFile(file))
|
||||
addJarClassPath(file, warn);
|
||||
}
|
||||
|
||||
// Adds referenced classpath elements from a jar's Class-Path
|
||||
// Manifest entry. In some future release, we may want to
|
||||
// update this code to recognize URLs rather than simple
|
||||
// filenames, but if we do, we should redo all path-related code.
|
||||
private void addJarClassPath(File jarFile, boolean warn) {
|
||||
try {
|
||||
for (File f: fsInfo.getJarClassPath(jarFile)) {
|
||||
addFile(f, warn);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("error.reading.file", jarFile, JavacFileManager.getMessage(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Base class for handling support for the representation of Locations.
|
||||
* Implementations are responsible for handling the interactions between
|
||||
* the command line options for a location, and API access via setLocation.
|
||||
* @see #initHandlers
|
||||
* @see #getHandler
|
||||
*/
|
||||
protected abstract class LocationHandler {
|
||||
final Location location;
|
||||
final Set<OptionName> options;
|
||||
|
||||
/**
|
||||
* Create a handler. The location and options provide a way to map
|
||||
* from a location or an option to the corresponding handler.
|
||||
* @see #initHandlers
|
||||
*/
|
||||
protected LocationHandler(Location location, OptionName... options) {
|
||||
this.location = location;
|
||||
this.options = options.length == 0 ?
|
||||
EnumSet.noneOf(OptionName.class):
|
||||
EnumSet.copyOf(Arrays.asList(options));
|
||||
}
|
||||
|
||||
// TODO: TEMPORARY, while Options still used for command line options
|
||||
void update(Options optionTable) {
|
||||
for (OptionName o: options) {
|
||||
String v = optionTable.get(o);
|
||||
if (v != null) {
|
||||
handleOption(o, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @see JavaFileManager#handleOption. */
|
||||
abstract boolean handleOption(OptionName option, String value);
|
||||
/** @see JavaFileManager#getLocation. */
|
||||
abstract Collection<File> getLocation();
|
||||
/** @see JavaFileManager#setLocation. */
|
||||
abstract void setLocation(Iterable<? extends File> files) throws IOException;
|
||||
}
|
||||
|
||||
/**
|
||||
* General purpose implementation for output locations,
|
||||
* such as -d/CLASS_OUTPUT and -s/SOURCE_OUTPUT.
|
||||
* All options are treated as equivalent (i.e. aliases.)
|
||||
* The value is a single file, possibly null.
|
||||
*/
|
||||
private class OutputLocationHandler extends LocationHandler {
|
||||
private File outputDir;
|
||||
|
||||
OutputLocationHandler(Location location, OptionName... options) {
|
||||
super(location, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean handleOption(OptionName option, String value) {
|
||||
if (!options.contains(option))
|
||||
return false;
|
||||
|
||||
// TODO: could/should validate outputDir exists and is a directory
|
||||
// need to decide how best to report issue for benefit of
|
||||
// direct API call on JavaFileManager.handleOption(specifies IAE)
|
||||
// vs. command line decoding.
|
||||
outputDir = new File(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
Collection<File> getLocation() {
|
||||
return (outputDir == null) ? null : Collections.singleton(outputDir);
|
||||
}
|
||||
|
||||
@Override
|
||||
void setLocation(Iterable<? extends File> files) throws IOException {
|
||||
if (files == null) {
|
||||
outputDir = null;
|
||||
} else {
|
||||
Iterator<? extends File> pathIter = files.iterator();
|
||||
if (!pathIter.hasNext())
|
||||
throw new IllegalArgumentException("empty path for directory");
|
||||
File dir = pathIter.next();
|
||||
if (pathIter.hasNext())
|
||||
throw new IllegalArgumentException("path too long for directory");
|
||||
if (!dir.exists())
|
||||
throw new FileNotFoundException(dir + ": does not exist");
|
||||
else if (!dir.isDirectory())
|
||||
throw new IOException(dir + ": not a directory");
|
||||
outputDir = dir;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* General purpose implementation for search path locations,
|
||||
* such as -sourcepath/SOURCE_PATH and -processorPath/ANNOTATION_PROCESS_PATH.
|
||||
* All options are treated as equivalent (i.e. aliases.)
|
||||
* The value is an ordered set of files and/or directories.
|
||||
*/
|
||||
private class SimpleLocationHandler extends LocationHandler {
|
||||
protected Collection<File> searchPath;
|
||||
|
||||
SimpleLocationHandler(Location location, OptionName... options) {
|
||||
super(location, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean handleOption(OptionName option, String value) {
|
||||
if (!options.contains(option))
|
||||
return false;
|
||||
searchPath = value == null ? null :
|
||||
Collections.unmodifiableCollection(computePath(value));
|
||||
return true;
|
||||
}
|
||||
|
||||
protected Path computePath(String value) {
|
||||
return new Path().addFiles(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
Collection<File> getLocation() {
|
||||
return searchPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
void setLocation(Iterable<? extends File> files) {
|
||||
Path p;
|
||||
if (files == null) {
|
||||
p = computePath(null);
|
||||
} else {
|
||||
p = new Path().addFiles(files);
|
||||
}
|
||||
searchPath = Collections.unmodifiableCollection(p);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtype of SimpleLocationHandler for -classpath/CLASS_PATH.
|
||||
* If no value is given, a default is provided, based on system properties
|
||||
* and other values.
|
||||
*/
|
||||
private class ClassPathLocationHandler extends SimpleLocationHandler {
|
||||
ClassPathLocationHandler() {
|
||||
super(StandardLocation.CLASS_PATH,
|
||||
OptionName.CLASSPATH, OptionName.CP);
|
||||
}
|
||||
|
||||
@Override
|
||||
Collection<File> getLocation() {
|
||||
lazy();
|
||||
return searchPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Path computePath(String value) {
|
||||
String cp = value;
|
||||
|
||||
// CLASSPATH environment variable when run from `javac'.
|
||||
if (cp == null) cp = System.getProperty("env.class.path");
|
||||
|
||||
// If invoked via a java VM (not the javac launcher), use the
|
||||
// platform class path
|
||||
if (cp == null && System.getProperty("application.home") == null)
|
||||
cp = System.getProperty("java.class.path");
|
||||
|
||||
// Default to current working directory.
|
||||
if (cp == null) cp = ".";
|
||||
|
||||
return new Path()
|
||||
.expandJarClassPaths(true) // Only search user jars for Class-Paths
|
||||
.emptyPathDefault(new File(".")) // Empty path elt ==> current directory
|
||||
.addFiles(cp);
|
||||
}
|
||||
|
||||
private void lazy() {
|
||||
if (searchPath == null)
|
||||
setLocation(null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom subtype of LocationHandler for PLATFORM_CLASS_PATH.
|
||||
* Various options are supported for different components of the
|
||||
* platform class path.
|
||||
* Setting a value with setLocation overrides all existing option values.
|
||||
* Setting any option overrides any value set with setLocation, and reverts
|
||||
* to using default values for options that have not been set.
|
||||
* Setting -bootclasspath or -Xbootclasspath overrides any existing
|
||||
* value for -Xbootclasspath/p: and -Xbootclasspath/a:.
|
||||
*/
|
||||
private class BootClassPathLocationHandler extends LocationHandler {
|
||||
private Collection<File> searchPath;
|
||||
final Map<OptionName, String> optionValues = new EnumMap<OptionName,String>(OptionName.class);
|
||||
|
||||
/**
|
||||
* rt.jar as found on the default bootclasspath.
|
||||
* If the user specified a bootclasspath, null is used.
|
||||
*/
|
||||
private File defaultBootClassPathRtJar = null;
|
||||
|
||||
/**
|
||||
* Is bootclasspath the default?
|
||||
*/
|
||||
private boolean isDefaultBootClassPath;
|
||||
|
||||
BootClassPathLocationHandler() {
|
||||
super(StandardLocation.PLATFORM_CLASS_PATH,
|
||||
OptionName.BOOTCLASSPATH, OptionName.XBOOTCLASSPATH,
|
||||
OptionName.XBOOTCLASSPATH_PREPEND,
|
||||
OptionName.XBOOTCLASSPATH_APPEND,
|
||||
OptionName.ENDORSEDDIRS, OptionName.DJAVA_ENDORSED_DIRS,
|
||||
OptionName.EXTDIRS, OptionName.DJAVA_EXT_DIRS);
|
||||
}
|
||||
|
||||
boolean isDefault() {
|
||||
lazy();
|
||||
return isDefaultBootClassPath;
|
||||
}
|
||||
|
||||
boolean isDefaultRtJar(File file) {
|
||||
lazy();
|
||||
return file.equals(defaultBootClassPathRtJar);
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean handleOption(OptionName option, String value) {
|
||||
if (!options.contains(option))
|
||||
return false;
|
||||
|
||||
option = canonicalize(option);
|
||||
optionValues.put(option, value);
|
||||
if (option == BOOTCLASSPATH) {
|
||||
optionValues.remove(XBOOTCLASSPATH_PREPEND);
|
||||
optionValues.remove(XBOOTCLASSPATH_APPEND);
|
||||
}
|
||||
searchPath = null; // reset to "uninitialized"
|
||||
return true;
|
||||
}
|
||||
// where
|
||||
// TODO: would be better if option aliasing was handled at a higher
|
||||
// level
|
||||
private OptionName canonicalize(OptionName option) {
|
||||
switch (option) {
|
||||
case XBOOTCLASSPATH:
|
||||
return OptionName.BOOTCLASSPATH;
|
||||
case DJAVA_ENDORSED_DIRS:
|
||||
return OptionName.ENDORSEDDIRS;
|
||||
case DJAVA_EXT_DIRS:
|
||||
return OptionName.EXTDIRS;
|
||||
default:
|
||||
return option;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
Collection<File> getLocation() {
|
||||
lazy();
|
||||
return searchPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
void setLocation(Iterable<? extends File> files) {
|
||||
if (files == null) {
|
||||
searchPath = null; // reset to "uninitialized"
|
||||
} else {
|
||||
defaultBootClassPathRtJar = null;
|
||||
isDefaultBootClassPath = false;
|
||||
Path p = new Path().addFiles(files, false);
|
||||
searchPath = Collections.unmodifiableCollection(p);
|
||||
optionValues.clear();
|
||||
}
|
||||
}
|
||||
|
||||
Path computePath() {
|
||||
defaultBootClassPathRtJar = null;
|
||||
Path path = new Path();
|
||||
|
||||
String bootclasspathOpt = optionValues.get(BOOTCLASSPATH);
|
||||
String endorseddirsOpt = optionValues.get(ENDORSEDDIRS);
|
||||
String extdirsOpt = optionValues.get(EXTDIRS);
|
||||
String xbootclasspathPrependOpt = optionValues.get(XBOOTCLASSPATH_PREPEND);
|
||||
String xbootclasspathAppendOpt = optionValues.get(XBOOTCLASSPATH_APPEND);
|
||||
|
||||
path.addFiles(xbootclasspathPrependOpt);
|
||||
|
||||
if (endorseddirsOpt != null)
|
||||
path.addDirectories(endorseddirsOpt);
|
||||
else
|
||||
path.addDirectories(System.getProperty("java.endorsed.dirs"), false);
|
||||
|
||||
if (bootclasspathOpt != null) {
|
||||
path.addFiles(bootclasspathOpt);
|
||||
} else {
|
||||
// Standard system classes for this compiler's release.
|
||||
String files = System.getProperty("sun.boot.class.path");
|
||||
path.addFiles(files, false);
|
||||
File rt_jar = new File("rt.jar");
|
||||
for (File file : getPathEntries(files)) {
|
||||
if (new File(file.getName()).equals(rt_jar))
|
||||
defaultBootClassPathRtJar = file;
|
||||
}
|
||||
}
|
||||
|
||||
path.addFiles(xbootclasspathAppendOpt);
|
||||
|
||||
// Strictly speaking, standard extensions are not bootstrap
|
||||
// classes, but we treat them identically, so we'll pretend
|
||||
// that they are.
|
||||
if (extdirsOpt != null)
|
||||
path.addDirectories(extdirsOpt);
|
||||
else
|
||||
path.addDirectories(System.getProperty("java.ext.dirs"), false);
|
||||
|
||||
isDefaultBootClassPath =
|
||||
(xbootclasspathPrependOpt == null) &&
|
||||
(bootclasspathOpt == null) &&
|
||||
(xbootclasspathAppendOpt == null);
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
private void lazy() {
|
||||
if (searchPath == null)
|
||||
searchPath = Collections.unmodifiableCollection(computePath());
|
||||
}
|
||||
}
|
||||
|
||||
Map<Location, LocationHandler> handlersForLocation;
|
||||
Map<OptionName, LocationHandler> handlersForOption;
|
||||
|
||||
void initHandlers() {
|
||||
handlersForLocation = new HashMap<Location, LocationHandler>();
|
||||
handlersForOption = new EnumMap<OptionName, LocationHandler>(OptionName.class);
|
||||
|
||||
LocationHandler[] handlers = {
|
||||
new BootClassPathLocationHandler(),
|
||||
new ClassPathLocationHandler(),
|
||||
new SimpleLocationHandler(StandardLocation.SOURCE_PATH, OptionName.SOURCEPATH),
|
||||
new SimpleLocationHandler(StandardLocation.ANNOTATION_PROCESSOR_PATH, OptionName.PROCESSORPATH),
|
||||
new OutputLocationHandler((StandardLocation.CLASS_OUTPUT), OptionName.D),
|
||||
new OutputLocationHandler((StandardLocation.SOURCE_OUTPUT), OptionName.S)
|
||||
};
|
||||
|
||||
for (LocationHandler h: handlers) {
|
||||
handlersForLocation.put(h.location, h);
|
||||
for (OptionName o: h.options)
|
||||
handlersForOption.put(o, h);
|
||||
}
|
||||
}
|
||||
|
||||
boolean handleOption(OptionName option, String value) {
|
||||
LocationHandler h = handlersForOption.get(option);
|
||||
return (h == null ? false : h.handleOption(option, value));
|
||||
}
|
||||
|
||||
Collection<File> getLocation(Location location) {
|
||||
LocationHandler h = getHandler(location);
|
||||
return (h == null ? null : h.getLocation());
|
||||
}
|
||||
|
||||
File getOutputLocation(Location location) {
|
||||
if (!location.isOutputLocation())
|
||||
throw new IllegalArgumentException();
|
||||
LocationHandler h = getHandler(location);
|
||||
return ((OutputLocationHandler) h).outputDir;
|
||||
}
|
||||
|
||||
void setLocation(Location location, Iterable<? extends File> files) throws IOException {
|
||||
LocationHandler h = getHandler(location);
|
||||
if (h == null) {
|
||||
if (location.isOutputLocation())
|
||||
h = new OutputLocationHandler(location);
|
||||
else
|
||||
h = new SimpleLocationHandler(location);
|
||||
handlersForLocation.put(location, h);
|
||||
}
|
||||
h.setLocation(files);
|
||||
}
|
||||
|
||||
protected LocationHandler getHandler(Location location) {
|
||||
location.getClass(); // null check
|
||||
lazy();
|
||||
return handlersForLocation.get(location);
|
||||
}
|
||||
|
||||
// TOGO
|
||||
protected void lazy() {
|
||||
if (!inited) {
|
||||
warn = lint.isEnabled(Lint.LintCategory.PATH);
|
||||
|
||||
for (LocationHandler h: handlersForLocation.values()) {
|
||||
h.update(options);
|
||||
}
|
||||
|
||||
inited = true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Is this the name of an archive file? */
|
||||
private boolean isArchive(File file) {
|
||||
String n = file.getName().toLowerCase();
|
||||
return fsInfo.isFile(file)
|
||||
&& (n.endsWith(".jar") || n.endsWith(".zip"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method for converting a search path string to an array
|
||||
* of directory and JAR file URLs.
|
||||
*
|
||||
* Note that this method is called by apt and the DocletInvoker.
|
||||
*
|
||||
* @param path the search path string
|
||||
* @return the resulting array of directory and JAR file URLs
|
||||
*/
|
||||
public static URL[] pathToURLs(String path) {
|
||||
StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
|
||||
URL[] urls = new URL[st.countTokens()];
|
||||
int count = 0;
|
||||
while (st.hasMoreTokens()) {
|
||||
URL url = fileToURL(new File(st.nextToken()));
|
||||
if (url != null) {
|
||||
urls[count++] = url;
|
||||
}
|
||||
}
|
||||
if (urls.length != count) {
|
||||
URL[] tmp = new URL[count];
|
||||
System.arraycopy(urls, 0, tmp, 0, count);
|
||||
urls = tmp;
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the directory or JAR file URL corresponding to the specified
|
||||
* local file name.
|
||||
*
|
||||
* @param file the File object
|
||||
* @return the resulting directory or JAR file URL, or null if unknown
|
||||
*/
|
||||
private static URL fileToURL(File file) {
|
||||
String name;
|
||||
try {
|
||||
name = file.getCanonicalPath();
|
||||
} catch (IOException e) {
|
||||
name = file.getAbsolutePath();
|
||||
}
|
||||
name = name.replace(File.separatorChar, '/');
|
||||
if (!name.startsWith("/")) {
|
||||
name = "/" + name;
|
||||
}
|
||||
// If the file does not exist, then assume that it's a directory
|
||||
if (!file.isFile()) {
|
||||
name = name + "/";
|
||||
}
|
||||
try {
|
||||
return new URL("file", "", name);
|
||||
} catch (MalformedURLException e) {
|
||||
throw new IllegalArgumentException(file.toString());
|
||||
}
|
||||
}
|
||||
}
|
@ -1,558 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package com.sun.tools.javac.file;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.zip.ZipFile;
|
||||
import javax.tools.JavaFileManager.Location;
|
||||
|
||||
import com.sun.tools.javac.code.Lint;
|
||||
import com.sun.tools.javac.util.Context;
|
||||
import com.sun.tools.javac.util.ListBuffer;
|
||||
import com.sun.tools.javac.util.Log;
|
||||
import com.sun.tools.javac.util.Options;
|
||||
|
||||
import static javax.tools.StandardLocation.*;
|
||||
import static com.sun.tools.javac.main.OptionName.*;
|
||||
|
||||
/** This class converts command line arguments, environment variables
|
||||
* and system properties (in File.pathSeparator-separated String form)
|
||||
* into a boot class path, user class path, and source path (in
|
||||
* Collection<String> form).
|
||||
*
|
||||
* <p><b>This is NOT part of any supported API.
|
||||
* If you write code that depends on this, you do so at your own risk.
|
||||
* This code and its internal interfaces are subject to change or
|
||||
* deletion without notice.</b>
|
||||
*/
|
||||
public class Paths {
|
||||
|
||||
/** The context key for the todo list */
|
||||
protected static final Context.Key<Paths> pathsKey =
|
||||
new Context.Key<Paths>();
|
||||
|
||||
/** Get the Paths instance for this context.
|
||||
* @param context the context
|
||||
* @return the Paths instance for this context
|
||||
*/
|
||||
public static Paths instance(Context context) {
|
||||
Paths instance = context.get(pathsKey);
|
||||
if (instance == null)
|
||||
instance = new Paths(context);
|
||||
return instance;
|
||||
}
|
||||
|
||||
/** The log to use for warning output */
|
||||
private Log log;
|
||||
|
||||
/** Collection of command-line options */
|
||||
private Options options;
|
||||
|
||||
/** Handler for -Xlint options */
|
||||
private Lint lint;
|
||||
|
||||
/** Access to (possibly cached) file info */
|
||||
private FSInfo fsInfo;
|
||||
|
||||
protected Paths(Context context) {
|
||||
context.put(pathsKey, this);
|
||||
pathsForLocation = new HashMap<Location,Path>(16);
|
||||
setContext(context);
|
||||
}
|
||||
|
||||
void setContext(Context context) {
|
||||
log = Log.instance(context);
|
||||
options = Options.instance(context);
|
||||
lint = Lint.instance(context);
|
||||
fsInfo = FSInfo.instance(context);
|
||||
}
|
||||
|
||||
/** Whether to warn about non-existent path elements */
|
||||
private boolean warn;
|
||||
|
||||
private Map<Location, Path> pathsForLocation;
|
||||
|
||||
private boolean inited = false; // TODO? caching bad?
|
||||
|
||||
/**
|
||||
* rt.jar as found on the default bootclass path. If the user specified a
|
||||
* bootclasspath, null is used.
|
||||
*/
|
||||
private File defaultBootClassPathRtJar = null;
|
||||
|
||||
/**
|
||||
* Is bootclasspath the default?
|
||||
*/
|
||||
private boolean isDefaultBootClassPath;
|
||||
|
||||
Path getPathForLocation(Location location) {
|
||||
Path path = pathsForLocation.get(location);
|
||||
if (path == null)
|
||||
setPathForLocation(location, null);
|
||||
return pathsForLocation.get(location);
|
||||
}
|
||||
|
||||
void setPathForLocation(Location location, Iterable<? extends File> path) {
|
||||
// TODO? if (inited) throw new IllegalStateException
|
||||
// TODO: otherwise reset sourceSearchPath, classSearchPath as needed
|
||||
Path p;
|
||||
if (path == null) {
|
||||
if (location == CLASS_PATH)
|
||||
p = computeUserClassPath();
|
||||
else if (location == PLATFORM_CLASS_PATH)
|
||||
p = computeBootClassPath(); // sets isDefaultBootClassPath
|
||||
else if (location == ANNOTATION_PROCESSOR_PATH)
|
||||
p = computeAnnotationProcessorPath();
|
||||
else if (location == SOURCE_PATH)
|
||||
p = computeSourcePath();
|
||||
else
|
||||
// no defaults for other paths
|
||||
p = null;
|
||||
} else {
|
||||
if (location == PLATFORM_CLASS_PATH) {
|
||||
defaultBootClassPathRtJar = null;
|
||||
isDefaultBootClassPath = false;
|
||||
}
|
||||
p = new Path();
|
||||
for (File f: path)
|
||||
p.addFile(f, warn); // TODO: is use of warn appropriate?
|
||||
}
|
||||
pathsForLocation.put(location, p);
|
||||
}
|
||||
|
||||
public boolean isDefaultBootClassPath() {
|
||||
lazy();
|
||||
return isDefaultBootClassPath;
|
||||
}
|
||||
|
||||
protected void lazy() {
|
||||
if (!inited) {
|
||||
warn = lint.isEnabled(Lint.LintCategory.PATH);
|
||||
|
||||
pathsForLocation.put(PLATFORM_CLASS_PATH, computeBootClassPath());
|
||||
pathsForLocation.put(CLASS_PATH, computeUserClassPath());
|
||||
pathsForLocation.put(SOURCE_PATH, computeSourcePath());
|
||||
|
||||
inited = true;
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<File> bootClassPath() {
|
||||
lazy();
|
||||
return Collections.unmodifiableCollection(getPathForLocation(PLATFORM_CLASS_PATH));
|
||||
}
|
||||
public Collection<File> userClassPath() {
|
||||
lazy();
|
||||
return Collections.unmodifiableCollection(getPathForLocation(CLASS_PATH));
|
||||
}
|
||||
public Collection<File> sourcePath() {
|
||||
lazy();
|
||||
Path p = getPathForLocation(SOURCE_PATH);
|
||||
return p == null || p.size() == 0
|
||||
? null
|
||||
: Collections.unmodifiableCollection(p);
|
||||
}
|
||||
|
||||
boolean isDefaultBootClassPathRtJar(File file) {
|
||||
return file.equals(defaultBootClassPathRtJar);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a path into its elements. Empty path elements will be ignored.
|
||||
* @param path The path to be split
|
||||
* @return The elements of the path
|
||||
*/
|
||||
private static Iterable<File> getPathEntries(String path) {
|
||||
return getPathEntries(path, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a path into its elements. If emptyPathDefault is not null, all
|
||||
* empty elements in the path, including empty elements at either end of
|
||||
* the path, will be replaced with the value of emptyPathDefault.
|
||||
* @param path The path to be split
|
||||
* @param emptyPathDefault The value to substitute for empty path elements,
|
||||
* or null, to ignore empty path elements
|
||||
* @return The elements of the path
|
||||
*/
|
||||
private static Iterable<File> getPathEntries(String path, File emptyPathDefault) {
|
||||
ListBuffer<File> entries = new ListBuffer<File>();
|
||||
int start = 0;
|
||||
while (start <= path.length()) {
|
||||
int sep = path.indexOf(File.pathSeparatorChar, start);
|
||||
if (sep == -1)
|
||||
sep = path.length();
|
||||
if (start < sep)
|
||||
entries.add(new File(path.substring(start, sep)));
|
||||
else if (emptyPathDefault != null)
|
||||
entries.add(emptyPathDefault);
|
||||
start = sep + 1;
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private class Path extends LinkedHashSet<File> {
|
||||
private static final long serialVersionUID = 0;
|
||||
|
||||
private boolean expandJarClassPaths = false;
|
||||
private Set<File> canonicalValues = new HashSet<File>();
|
||||
|
||||
public Path expandJarClassPaths(boolean x) {
|
||||
expandJarClassPaths = x;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** What to use when path element is the empty string */
|
||||
private File emptyPathDefault = null;
|
||||
|
||||
public Path emptyPathDefault(File x) {
|
||||
emptyPathDefault = x;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Path() { super(); }
|
||||
|
||||
public Path addDirectories(String dirs, boolean warn) {
|
||||
boolean prev = expandJarClassPaths;
|
||||
expandJarClassPaths = true;
|
||||
try {
|
||||
if (dirs != null)
|
||||
for (File dir : getPathEntries(dirs))
|
||||
addDirectory(dir, warn);
|
||||
return this;
|
||||
} finally {
|
||||
expandJarClassPaths = prev;
|
||||
}
|
||||
}
|
||||
|
||||
public Path addDirectories(String dirs) {
|
||||
return addDirectories(dirs, warn);
|
||||
}
|
||||
|
||||
private void addDirectory(File dir, boolean warn) {
|
||||
if (!dir.isDirectory()) {
|
||||
if (warn)
|
||||
log.warning(Lint.LintCategory.PATH,
|
||||
"dir.path.element.not.found", dir);
|
||||
return;
|
||||
}
|
||||
|
||||
File[] files = dir.listFiles();
|
||||
if (files == null)
|
||||
return;
|
||||
|
||||
for (File direntry : files) {
|
||||
if (isArchive(direntry))
|
||||
addFile(direntry, warn);
|
||||
}
|
||||
}
|
||||
|
||||
public Path addFiles(String files, boolean warn) {
|
||||
if (files != null) {
|
||||
for (File file : getPathEntries(files, emptyPathDefault))
|
||||
addFile(file, warn);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Path addFiles(String files) {
|
||||
return addFiles(files, warn);
|
||||
}
|
||||
|
||||
public void addFile(File file, boolean warn) {
|
||||
if (contains(file)) {
|
||||
// discard duplicates
|
||||
return;
|
||||
}
|
||||
|
||||
if (! fsInfo.exists(file)) {
|
||||
/* No such file or directory exists */
|
||||
if (warn) {
|
||||
log.warning(Lint.LintCategory.PATH,
|
||||
"path.element.not.found", file);
|
||||
}
|
||||
super.add(file);
|
||||
return;
|
||||
}
|
||||
|
||||
File canonFile = fsInfo.getCanonicalFile(file);
|
||||
if (canonicalValues.contains(canonFile)) {
|
||||
/* Discard duplicates and avoid infinite recursion */
|
||||
return;
|
||||
}
|
||||
|
||||
if (fsInfo.isFile(file)) {
|
||||
/* File is an ordinary file. */
|
||||
if (!isArchive(file)) {
|
||||
/* Not a recognized extension; open it to see if
|
||||
it looks like a valid zip file. */
|
||||
try {
|
||||
ZipFile z = new ZipFile(file);
|
||||
z.close();
|
||||
if (warn) {
|
||||
log.warning(Lint.LintCategory.PATH,
|
||||
"unexpected.archive.file", file);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// FIXME: include e.getLocalizedMessage in warning
|
||||
if (warn) {
|
||||
log.warning(Lint.LintCategory.PATH,
|
||||
"invalid.archive.file", file);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Now what we have left is either a directory or a file name
|
||||
conforming to archive naming convention */
|
||||
super.add(file);
|
||||
canonicalValues.add(canonFile);
|
||||
|
||||
if (expandJarClassPaths && fsInfo.isFile(file))
|
||||
addJarClassPath(file, warn);
|
||||
}
|
||||
|
||||
// Adds referenced classpath elements from a jar's Class-Path
|
||||
// Manifest entry. In some future release, we may want to
|
||||
// update this code to recognize URLs rather than simple
|
||||
// filenames, but if we do, we should redo all path-related code.
|
||||
private void addJarClassPath(File jarFile, boolean warn) {
|
||||
try {
|
||||
for (File f: fsInfo.getJarClassPath(jarFile)) {
|
||||
addFile(f, warn);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("error.reading.file", jarFile, JavacFileManager.getMessage(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Path computeBootClassPath() {
|
||||
defaultBootClassPathRtJar = null;
|
||||
Path path = new Path();
|
||||
|
||||
String bootclasspathOpt = options.get(BOOTCLASSPATH);
|
||||
String endorseddirsOpt = options.get(ENDORSEDDIRS);
|
||||
String extdirsOpt = options.get(EXTDIRS);
|
||||
String xbootclasspathPrependOpt = options.get(XBOOTCLASSPATH_PREPEND);
|
||||
String xbootclasspathAppendOpt = options.get(XBOOTCLASSPATH_APPEND);
|
||||
|
||||
path.addFiles(xbootclasspathPrependOpt);
|
||||
|
||||
if (endorseddirsOpt != null)
|
||||
path.addDirectories(endorseddirsOpt);
|
||||
else
|
||||
path.addDirectories(System.getProperty("java.endorsed.dirs"), false);
|
||||
|
||||
if (bootclasspathOpt != null) {
|
||||
path.addFiles(bootclasspathOpt);
|
||||
} else {
|
||||
// Standard system classes for this compiler's release.
|
||||
String files = System.getProperty("sun.boot.class.path");
|
||||
path.addFiles(files, false);
|
||||
File rt_jar = new File("rt.jar");
|
||||
for (File file : getPathEntries(files)) {
|
||||
if (new File(file.getName()).equals(rt_jar))
|
||||
defaultBootClassPathRtJar = file;
|
||||
}
|
||||
}
|
||||
|
||||
path.addFiles(xbootclasspathAppendOpt);
|
||||
|
||||
// Strictly speaking, standard extensions are not bootstrap
|
||||
// classes, but we treat them identically, so we'll pretend
|
||||
// that they are.
|
||||
if (extdirsOpt != null)
|
||||
path.addDirectories(extdirsOpt);
|
||||
else
|
||||
path.addDirectories(System.getProperty("java.ext.dirs"), false);
|
||||
|
||||
isDefaultBootClassPath =
|
||||
(xbootclasspathPrependOpt == null) &&
|
||||
(bootclasspathOpt == null) &&
|
||||
(xbootclasspathAppendOpt == null);
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
private Path computeUserClassPath() {
|
||||
String cp = options.get(CLASSPATH);
|
||||
|
||||
// CLASSPATH environment variable when run from `javac'.
|
||||
if (cp == null) cp = System.getProperty("env.class.path");
|
||||
|
||||
// If invoked via a java VM (not the javac launcher), use the
|
||||
// platform class path
|
||||
if (cp == null && System.getProperty("application.home") == null)
|
||||
cp = System.getProperty("java.class.path");
|
||||
|
||||
// Default to current working directory.
|
||||
if (cp == null) cp = ".";
|
||||
|
||||
return new Path()
|
||||
.expandJarClassPaths(true) // Only search user jars for Class-Paths
|
||||
.emptyPathDefault(new File(".")) // Empty path elt ==> current directory
|
||||
.addFiles(cp);
|
||||
}
|
||||
|
||||
private Path computeSourcePath() {
|
||||
String sourcePathArg = options.get(SOURCEPATH);
|
||||
if (sourcePathArg == null)
|
||||
return null;
|
||||
|
||||
return new Path().addFiles(sourcePathArg);
|
||||
}
|
||||
|
||||
private Path computeAnnotationProcessorPath() {
|
||||
String processorPathArg = options.get(PROCESSORPATH);
|
||||
if (processorPathArg == null)
|
||||
return null;
|
||||
|
||||
return new Path().addFiles(processorPathArg);
|
||||
}
|
||||
|
||||
/** The actual effective locations searched for sources */
|
||||
private Path sourceSearchPath;
|
||||
|
||||
public Collection<File> sourceSearchPath() {
|
||||
if (sourceSearchPath == null) {
|
||||
lazy();
|
||||
Path sourcePath = getPathForLocation(SOURCE_PATH);
|
||||
Path userClassPath = getPathForLocation(CLASS_PATH);
|
||||
sourceSearchPath = sourcePath != null ? sourcePath : userClassPath;
|
||||
}
|
||||
return Collections.unmodifiableCollection(sourceSearchPath);
|
||||
}
|
||||
|
||||
/** The actual effective locations searched for classes */
|
||||
private Path classSearchPath;
|
||||
|
||||
public Collection<File> classSearchPath() {
|
||||
if (classSearchPath == null) {
|
||||
lazy();
|
||||
Path bootClassPath = getPathForLocation(PLATFORM_CLASS_PATH);
|
||||
Path userClassPath = getPathForLocation(CLASS_PATH);
|
||||
classSearchPath = new Path();
|
||||
classSearchPath.addAll(bootClassPath);
|
||||
classSearchPath.addAll(userClassPath);
|
||||
}
|
||||
return Collections.unmodifiableCollection(classSearchPath);
|
||||
}
|
||||
|
||||
/** The actual effective locations for non-source, non-class files */
|
||||
private Path otherSearchPath;
|
||||
|
||||
Collection<File> otherSearchPath() {
|
||||
if (otherSearchPath == null) {
|
||||
lazy();
|
||||
Path userClassPath = getPathForLocation(CLASS_PATH);
|
||||
Path sourcePath = getPathForLocation(SOURCE_PATH);
|
||||
if (sourcePath == null)
|
||||
otherSearchPath = userClassPath;
|
||||
else {
|
||||
otherSearchPath = new Path();
|
||||
otherSearchPath.addAll(userClassPath);
|
||||
otherSearchPath.addAll(sourcePath);
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableCollection(otherSearchPath);
|
||||
}
|
||||
|
||||
/** Is this the name of an archive file? */
|
||||
private boolean isArchive(File file) {
|
||||
String n = file.getName().toLowerCase();
|
||||
return fsInfo.isFile(file)
|
||||
&& (n.endsWith(".jar") || n.endsWith(".zip"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility method for converting a search path string to an array
|
||||
* of directory and JAR file URLs.
|
||||
*
|
||||
* Note that this method is called by apt and the DocletInvoker.
|
||||
*
|
||||
* @param path the search path string
|
||||
* @return the resulting array of directory and JAR file URLs
|
||||
*/
|
||||
public static URL[] pathToURLs(String path) {
|
||||
StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
|
||||
URL[] urls = new URL[st.countTokens()];
|
||||
int count = 0;
|
||||
while (st.hasMoreTokens()) {
|
||||
URL url = fileToURL(new File(st.nextToken()));
|
||||
if (url != null) {
|
||||
urls[count++] = url;
|
||||
}
|
||||
}
|
||||
if (urls.length != count) {
|
||||
URL[] tmp = new URL[count];
|
||||
System.arraycopy(urls, 0, tmp, 0, count);
|
||||
urls = tmp;
|
||||
}
|
||||
return urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the directory or JAR file URL corresponding to the specified
|
||||
* local file name.
|
||||
*
|
||||
* @param file the File object
|
||||
* @return the resulting directory or JAR file URL, or null if unknown
|
||||
*/
|
||||
private static URL fileToURL(File file) {
|
||||
String name;
|
||||
try {
|
||||
name = file.getCanonicalPath();
|
||||
} catch (IOException e) {
|
||||
name = file.getAbsolutePath();
|
||||
}
|
||||
name = name.replace(File.separatorChar, '/');
|
||||
if (!name.startsWith("/")) {
|
||||
name = "/" + name;
|
||||
}
|
||||
// If the file does not exist, then assume that it's a directory
|
||||
if (!file.isFile()) {
|
||||
name = name + "/";
|
||||
}
|
||||
try {
|
||||
return new URL("file", "", name);
|
||||
} catch (MalformedURLException e) {
|
||||
throw new IllegalArgumentException(file.toString());
|
||||
}
|
||||
}
|
||||
}
|
@ -1542,7 +1542,28 @@ public class Code {
|
||||
*/
|
||||
public void addCatch(
|
||||
char startPc, char endPc, char handlerPc, char catchType) {
|
||||
catchInfo.append(new char[]{startPc, endPc, handlerPc, catchType});
|
||||
catchInfo.append(new char[]{startPc, endPc, handlerPc, catchType});
|
||||
}
|
||||
|
||||
|
||||
public void compressCatchTable() {
|
||||
ListBuffer<char[]> compressedCatchInfo = ListBuffer.lb();
|
||||
List<Integer> handlerPcs = List.nil();
|
||||
for (char[] catchEntry : catchInfo.elems) {
|
||||
handlerPcs = handlerPcs.prepend((int)catchEntry[2]);
|
||||
}
|
||||
for (char[] catchEntry : catchInfo.elems) {
|
||||
int startpc = catchEntry[0];
|
||||
int endpc = catchEntry[1];
|
||||
if (startpc == endpc ||
|
||||
(startpc == (endpc - 1) &&
|
||||
handlerPcs.contains(startpc))) {
|
||||
continue;
|
||||
} else {
|
||||
compressedCatchInfo.append(catchEntry);
|
||||
}
|
||||
}
|
||||
catchInfo = compressedCatchInfo;
|
||||
}
|
||||
|
||||
|
||||
|
@ -959,6 +959,9 @@ public class Gen extends JCTree.Visitor {
|
||||
code.lastFrame = null;
|
||||
code.frameBeforeLast = null;
|
||||
}
|
||||
|
||||
//compress exception table
|
||||
code.compressCatchTable();
|
||||
}
|
||||
}
|
||||
|
||||
@ -1437,7 +1440,6 @@ public class Gen extends JCTree.Visitor {
|
||||
code.markDead();
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve all breaks.
|
||||
code.resolve(exitChain);
|
||||
|
||||
@ -1496,23 +1498,21 @@ public class Gen extends JCTree.Visitor {
|
||||
void registerCatch(DiagnosticPosition pos,
|
||||
int startpc, int endpc,
|
||||
int handler_pc, int catch_type) {
|
||||
if (startpc != endpc) {
|
||||
char startpc1 = (char)startpc;
|
||||
char endpc1 = (char)endpc;
|
||||
char handler_pc1 = (char)handler_pc;
|
||||
if (startpc1 == startpc &&
|
||||
endpc1 == endpc &&
|
||||
handler_pc1 == handler_pc) {
|
||||
code.addCatch(startpc1, endpc1, handler_pc1,
|
||||
(char)catch_type);
|
||||
char startpc1 = (char)startpc;
|
||||
char endpc1 = (char)endpc;
|
||||
char handler_pc1 = (char)handler_pc;
|
||||
if (startpc1 == startpc &&
|
||||
endpc1 == endpc &&
|
||||
handler_pc1 == handler_pc) {
|
||||
code.addCatch(startpc1, endpc1, handler_pc1,
|
||||
(char)catch_type);
|
||||
} else {
|
||||
if (!useJsrLocally && !target.generateStackMapTable()) {
|
||||
useJsrLocally = true;
|
||||
throw new CodeSizeOverflow();
|
||||
} else {
|
||||
if (!useJsrLocally && !target.generateStackMapTable()) {
|
||||
useJsrLocally = true;
|
||||
throw new CodeSizeOverflow();
|
||||
} else {
|
||||
log.error(pos, "limit.code.too.large.for.try.stmt");
|
||||
nerrs++;
|
||||
}
|
||||
log.error(pos, "limit.code.too.large.for.try.stmt");
|
||||
nerrs++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -25,9 +25,7 @@
|
||||
|
||||
package com.sun.tools.javac.nio;
|
||||
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
@ -60,7 +58,6 @@ import javax.tools.StandardLocation;
|
||||
import static java.nio.file.FileVisitOption.*;
|
||||
import static javax.tools.StandardLocation.*;
|
||||
|
||||
import com.sun.tools.javac.file.Paths;
|
||||
import com.sun.tools.javac.util.BaseFileManager;
|
||||
import com.sun.tools.javac.util.Context;
|
||||
import com.sun.tools.javac.util.List;
|
||||
@ -125,9 +122,8 @@ public class JavacPathFileManager extends BaseFileManager implements PathFileMan
|
||||
* Set the context for JavacPathFileManager.
|
||||
*/
|
||||
@Override
|
||||
protected void setContext(Context context) {
|
||||
public void setContext(Context context) {
|
||||
super.setContext(context);
|
||||
searchPaths = Paths.instance(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -173,7 +169,7 @@ public class JavacPathFileManager extends BaseFileManager implements PathFileMan
|
||||
|
||||
@Override
|
||||
public boolean isDefaultBootClassPath() {
|
||||
return searchPaths.isDefaultBootClassPath();
|
||||
return locations.isDefaultBootClassPath();
|
||||
}
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="Location handling">
|
||||
@ -231,13 +227,13 @@ public class JavacPathFileManager extends BaseFileManager implements PathFileMan
|
||||
if (locn instanceof StandardLocation) {
|
||||
switch ((StandardLocation) locn) {
|
||||
case CLASS_PATH:
|
||||
files = searchPaths.userClassPath();
|
||||
files = locations.userClassPath();
|
||||
break;
|
||||
case PLATFORM_CLASS_PATH:
|
||||
files = searchPaths.bootClassPath();
|
||||
files = locations.bootClassPath();
|
||||
break;
|
||||
case SOURCE_PATH:
|
||||
files = searchPaths.sourcePath();
|
||||
files = locations.sourcePath();
|
||||
break;
|
||||
case CLASS_OUTPUT: {
|
||||
String arg = options.get(D);
|
||||
@ -272,7 +268,6 @@ public class JavacPathFileManager extends BaseFileManager implements PathFileMan
|
||||
private boolean inited = false;
|
||||
|
||||
private Map<Location, PathsForLocation> pathsForLocation;
|
||||
private Paths searchPaths;
|
||||
|
||||
private static class PathsForLocation extends LinkedHashSet<Path> {
|
||||
private static final long serialVersionUID = 6788510222394486733L;
|
||||
|
@ -67,14 +67,14 @@ public class EndPosParser extends JavacParser {
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
protected <T extends JCTree> T to(T t) {
|
||||
storeEnd(t, S.endPos());
|
||||
storeEnd(t, token.endPos);
|
||||
return t;
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
protected <T extends JCTree> T toP(T t) {
|
||||
storeEnd(t, S.prevEndPos());
|
||||
storeEnd(t, S.prevToken().endPos);
|
||||
return t;
|
||||
}
|
||||
|
||||
@ -88,7 +88,7 @@ public class EndPosParser extends JavacParser {
|
||||
/** {@inheritDoc} */
|
||||
@Override
|
||||
JCExpression parExpression() {
|
||||
int pos = S.pos();
|
||||
int pos = token.pos;
|
||||
JCExpression t = super.parExpression();
|
||||
return toP(F.at(pos).Parens(t));
|
||||
}
|
||||
|
@ -0,0 +1,896 @@
|
||||
/*
|
||||
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package com.sun.tools.javac.parser;
|
||||
|
||||
import java.nio.CharBuffer;
|
||||
import com.sun.tools.javac.code.Source;
|
||||
import com.sun.tools.javac.util.*;
|
||||
|
||||
|
||||
import static com.sun.tools.javac.parser.Tokens.*;
|
||||
import static com.sun.tools.javac.util.LayoutCharacters.*;
|
||||
|
||||
/** The lexical analyzer maps an input stream consisting of
|
||||
* ASCII characters and Unicode escapes into a token sequence.
|
||||
*
|
||||
* <p><b>This is NOT part of any supported API.
|
||||
* If you write code that depends on this, you do so at your own risk.
|
||||
* This code and its internal interfaces are subject to change or
|
||||
* deletion without notice.</b>
|
||||
*/
|
||||
public class JavaTokenizer {
|
||||
|
||||
private static boolean scannerDebug = false;
|
||||
|
||||
/** Allow hex floating-point literals.
|
||||
*/
|
||||
private boolean allowHexFloats;
|
||||
|
||||
/** Allow binary literals.
|
||||
*/
|
||||
private boolean allowBinaryLiterals;
|
||||
|
||||
/** Allow underscores in literals.
|
||||
*/
|
||||
private boolean allowUnderscoresInLiterals;
|
||||
|
||||
/** The source language setting.
|
||||
*/
|
||||
private Source source;
|
||||
|
||||
/** The log to be used for error reporting.
|
||||
*/
|
||||
private final Log log;
|
||||
|
||||
/** The name table. */
|
||||
private final Names names;
|
||||
|
||||
/** The token factory. */
|
||||
private final Tokens tokens;
|
||||
|
||||
/** The token kind, set by nextToken().
|
||||
*/
|
||||
protected TokenKind tk;
|
||||
|
||||
/** The token's radix, set by nextToken().
|
||||
*/
|
||||
protected int radix;
|
||||
|
||||
/** The token's name, set by nextToken().
|
||||
*/
|
||||
protected Name name;
|
||||
|
||||
/** The position where a lexical error occurred;
|
||||
*/
|
||||
protected int errPos = Position.NOPOS;
|
||||
|
||||
/** Has a @deprecated been encountered in last doc comment?
|
||||
* this needs to be reset by client.
|
||||
*/
|
||||
protected boolean deprecatedFlag = false;
|
||||
|
||||
/** A character buffer for saved chars.
|
||||
*/
|
||||
protected char[] sbuf = new char[128];
|
||||
protected int sp;
|
||||
|
||||
protected UnicodeReader reader;
|
||||
|
||||
private static final boolean hexFloatsWork = hexFloatsWork();
|
||||
private static boolean hexFloatsWork() {
|
||||
try {
|
||||
Float.valueOf("0x1.0p1");
|
||||
return true;
|
||||
} catch (NumberFormatException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a scanner from the input array. This method might
|
||||
* modify the array. To avoid copying the input array, ensure
|
||||
* that {@code inputLength < input.length} or
|
||||
* {@code input[input.length -1]} is a white space character.
|
||||
*
|
||||
* @param fac the factory which created this Scanner
|
||||
* @param input the input, might be modified
|
||||
* @param inputLength the size of the input.
|
||||
* Must be positive and less than or equal to input.length.
|
||||
*/
|
||||
protected JavaTokenizer(ScannerFactory fac, CharBuffer buf) {
|
||||
this(fac, new UnicodeReader(fac, buf));
|
||||
}
|
||||
|
||||
protected JavaTokenizer(ScannerFactory fac, char[] buf, int inputLength) {
|
||||
this(fac, new UnicodeReader(fac, buf, inputLength));
|
||||
}
|
||||
|
||||
protected JavaTokenizer(ScannerFactory fac, UnicodeReader reader) {
|
||||
log = fac.log;
|
||||
names = fac.names;
|
||||
tokens = fac.tokens;
|
||||
source = fac.source;
|
||||
this.reader = reader;
|
||||
allowBinaryLiterals = source.allowBinaryLiterals();
|
||||
allowHexFloats = source.allowHexFloats();
|
||||
allowUnderscoresInLiterals = source.allowUnderscoresInLiterals();
|
||||
}
|
||||
|
||||
/** Report an error at the given position using the provided arguments.
|
||||
*/
|
||||
protected void lexError(int pos, String key, Object... args) {
|
||||
log.error(pos, key, args);
|
||||
tk = TokenKind.ERROR;
|
||||
errPos = pos;
|
||||
}
|
||||
|
||||
/** Read next character in comment, skipping over double '\' characters.
|
||||
*/
|
||||
protected void scanCommentChar() {
|
||||
reader.scanChar();
|
||||
if (reader.ch == '\\') {
|
||||
if (reader.peekChar() == '\\' && !reader.isUnicode()) {
|
||||
reader.skipChar();
|
||||
} else {
|
||||
reader.convertUnicode();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Append a character to sbuf.
|
||||
*/
|
||||
private void putChar(char ch) {
|
||||
if (sp == sbuf.length) {
|
||||
char[] newsbuf = new char[sbuf.length * 2];
|
||||
System.arraycopy(sbuf, 0, newsbuf, 0, sbuf.length);
|
||||
sbuf = newsbuf;
|
||||
}
|
||||
sbuf[sp++] = ch;
|
||||
}
|
||||
|
||||
/** Read next character in character or string literal and copy into sbuf.
|
||||
*/
|
||||
private void scanLitChar(int pos) {
|
||||
if (reader.ch == '\\') {
|
||||
if (reader.peekChar() == '\\' && !reader.isUnicode()) {
|
||||
reader.skipChar();
|
||||
putChar('\\');
|
||||
reader.scanChar();
|
||||
} else {
|
||||
reader.scanChar();
|
||||
switch (reader.ch) {
|
||||
case '0': case '1': case '2': case '3':
|
||||
case '4': case '5': case '6': case '7':
|
||||
char leadch = reader.ch;
|
||||
int oct = reader.digit(pos, 8);
|
||||
reader.scanChar();
|
||||
if ('0' <= reader.ch && reader.ch <= '7') {
|
||||
oct = oct * 8 + reader.digit(pos, 8);
|
||||
reader.scanChar();
|
||||
if (leadch <= '3' && '0' <= reader.ch && reader.ch <= '7') {
|
||||
oct = oct * 8 + reader.digit(pos, 8);
|
||||
reader.scanChar();
|
||||
}
|
||||
}
|
||||
putChar((char)oct);
|
||||
break;
|
||||
case 'b':
|
||||
putChar('\b'); reader.scanChar(); break;
|
||||
case 't':
|
||||
putChar('\t'); reader.scanChar(); break;
|
||||
case 'n':
|
||||
putChar('\n'); reader.scanChar(); break;
|
||||
case 'f':
|
||||
putChar('\f'); reader.scanChar(); break;
|
||||
case 'r':
|
||||
putChar('\r'); reader.scanChar(); break;
|
||||
case '\'':
|
||||
putChar('\''); reader.scanChar(); break;
|
||||
case '\"':
|
||||
putChar('\"'); reader.scanChar(); break;
|
||||
case '\\':
|
||||
putChar('\\'); reader.scanChar(); break;
|
||||
default:
|
||||
lexError(reader.bp, "illegal.esc.char");
|
||||
}
|
||||
}
|
||||
} else if (reader.bp != reader.buflen) {
|
||||
putChar(reader.ch); reader.scanChar();
|
||||
}
|
||||
}
|
||||
|
||||
private void scanDigits(int pos, int digitRadix) {
|
||||
char saveCh;
|
||||
int savePos;
|
||||
do {
|
||||
if (reader.ch != '_') {
|
||||
putChar(reader.ch);
|
||||
} else {
|
||||
if (!allowUnderscoresInLiterals) {
|
||||
lexError(pos, "unsupported.underscore.lit", source.name);
|
||||
allowUnderscoresInLiterals = true;
|
||||
}
|
||||
}
|
||||
saveCh = reader.ch;
|
||||
savePos = reader.bp;
|
||||
reader.scanChar();
|
||||
} while (reader.digit(pos, digitRadix) >= 0 || reader.ch == '_');
|
||||
if (saveCh == '_')
|
||||
lexError(savePos, "illegal.underscore");
|
||||
}
|
||||
|
||||
/** Read fractional part of hexadecimal floating point number.
|
||||
*/
|
||||
private void scanHexExponentAndSuffix(int pos) {
|
||||
if (reader.ch == 'p' || reader.ch == 'P') {
|
||||
putChar(reader.ch);
|
||||
reader.scanChar();
|
||||
skipIllegalUnderscores();
|
||||
if (reader.ch == '+' || reader.ch == '-') {
|
||||
putChar(reader.ch);
|
||||
reader.scanChar();
|
||||
}
|
||||
skipIllegalUnderscores();
|
||||
if ('0' <= reader.ch && reader.ch <= '9') {
|
||||
scanDigits(pos, 10);
|
||||
if (!allowHexFloats) {
|
||||
lexError(pos, "unsupported.fp.lit", source.name);
|
||||
allowHexFloats = true;
|
||||
}
|
||||
else if (!hexFloatsWork)
|
||||
lexError(pos, "unsupported.cross.fp.lit");
|
||||
} else
|
||||
lexError(pos, "malformed.fp.lit");
|
||||
} else {
|
||||
lexError(pos, "malformed.fp.lit");
|
||||
}
|
||||
if (reader.ch == 'f' || reader.ch == 'F') {
|
||||
putChar(reader.ch);
|
||||
reader.scanChar();
|
||||
tk = TokenKind.FLOATLITERAL;
|
||||
radix = 16;
|
||||
} else {
|
||||
if (reader.ch == 'd' || reader.ch == 'D') {
|
||||
putChar(reader.ch);
|
||||
reader.scanChar();
|
||||
}
|
||||
tk = TokenKind.DOUBLELITERAL;
|
||||
radix = 16;
|
||||
}
|
||||
}
|
||||
|
||||
/** Read fractional part of floating point number.
|
||||
*/
|
||||
private void scanFraction(int pos) {
|
||||
skipIllegalUnderscores();
|
||||
if ('0' <= reader.ch && reader.ch <= '9') {
|
||||
scanDigits(pos, 10);
|
||||
}
|
||||
int sp1 = sp;
|
||||
if (reader.ch == 'e' || reader.ch == 'E') {
|
||||
putChar(reader.ch);
|
||||
reader.scanChar();
|
||||
skipIllegalUnderscores();
|
||||
if (reader.ch == '+' || reader.ch == '-') {
|
||||
putChar(reader.ch);
|
||||
reader.scanChar();
|
||||
}
|
||||
skipIllegalUnderscores();
|
||||
if ('0' <= reader.ch && reader.ch <= '9') {
|
||||
scanDigits(pos, 10);
|
||||
return;
|
||||
}
|
||||
lexError(pos, "malformed.fp.lit");
|
||||
sp = sp1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Read fractional part and 'd' or 'f' suffix of floating point number.
|
||||
*/
|
||||
private void scanFractionAndSuffix(int pos) {
|
||||
radix = 10;
|
||||
scanFraction(pos);
|
||||
if (reader.ch == 'f' || reader.ch == 'F') {
|
||||
putChar(reader.ch);
|
||||
reader.scanChar();
|
||||
tk = TokenKind.FLOATLITERAL;
|
||||
} else {
|
||||
if (reader.ch == 'd' || reader.ch == 'D') {
|
||||
putChar(reader.ch);
|
||||
reader.scanChar();
|
||||
}
|
||||
tk = TokenKind.DOUBLELITERAL;
|
||||
}
|
||||
}
|
||||
|
||||
/** Read fractional part and 'd' or 'f' suffix of floating point number.
|
||||
*/
|
||||
private void scanHexFractionAndSuffix(int pos, boolean seendigit) {
|
||||
radix = 16;
|
||||
Assert.check(reader.ch == '.');
|
||||
putChar(reader.ch);
|
||||
reader.scanChar();
|
||||
skipIllegalUnderscores();
|
||||
if (reader.digit(pos, 16) >= 0) {
|
||||
seendigit = true;
|
||||
scanDigits(pos, 16);
|
||||
}
|
||||
if (!seendigit)
|
||||
lexError(pos, "invalid.hex.number");
|
||||
else
|
||||
scanHexExponentAndSuffix(pos);
|
||||
}
|
||||
|
||||
private void skipIllegalUnderscores() {
|
||||
if (reader.ch == '_') {
|
||||
lexError(reader.bp, "illegal.underscore");
|
||||
while (reader.ch == '_')
|
||||
reader.scanChar();
|
||||
}
|
||||
}
|
||||
|
||||
/** Read a number.
|
||||
* @param radix The radix of the number; one of 2, j8, 10, 16.
|
||||
*/
|
||||
private void scanNumber(int pos, int radix) {
|
||||
// for octal, allow base-10 digit in case it's a float literal
|
||||
this.radix = radix;
|
||||
int digitRadix = (radix == 8 ? 10 : radix);
|
||||
boolean seendigit = false;
|
||||
if (reader.digit(pos, digitRadix) >= 0) {
|
||||
seendigit = true;
|
||||
scanDigits(pos, digitRadix);
|
||||
}
|
||||
if (radix == 16 && reader.ch == '.') {
|
||||
scanHexFractionAndSuffix(pos, seendigit);
|
||||
} else if (seendigit && radix == 16 && (reader.ch == 'p' || reader.ch == 'P')) {
|
||||
scanHexExponentAndSuffix(pos);
|
||||
} else if (digitRadix == 10 && reader.ch == '.') {
|
||||
putChar(reader.ch);
|
||||
reader.scanChar();
|
||||
scanFractionAndSuffix(pos);
|
||||
} else if (digitRadix == 10 &&
|
||||
(reader.ch == 'e' || reader.ch == 'E' ||
|
||||
reader.ch == 'f' || reader.ch == 'F' ||
|
||||
reader.ch == 'd' || reader.ch == 'D')) {
|
||||
scanFractionAndSuffix(pos);
|
||||
} else {
|
||||
if (reader.ch == 'l' || reader.ch == 'L') {
|
||||
reader.scanChar();
|
||||
tk = TokenKind.LONGLITERAL;
|
||||
} else {
|
||||
tk = TokenKind.INTLITERAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Read an identifier.
|
||||
*/
|
||||
private void scanIdent() {
|
||||
boolean isJavaIdentifierPart;
|
||||
char high;
|
||||
do {
|
||||
if (sp == sbuf.length) putChar(reader.ch); else sbuf[sp++] = reader.ch;
|
||||
// optimization, was: putChar(reader.ch);
|
||||
|
||||
reader.scanChar();
|
||||
switch (reader.ch) {
|
||||
case 'A': case 'B': case 'C': case 'D': case 'E':
|
||||
case 'F': case 'G': case 'H': case 'I': case 'J':
|
||||
case 'K': case 'L': case 'M': case 'N': case 'O':
|
||||
case 'P': case 'Q': case 'R': case 'S': case 'T':
|
||||
case 'U': case 'V': case 'W': case 'X': case 'Y':
|
||||
case 'Z':
|
||||
case 'a': case 'b': case 'c': case 'd': case 'e':
|
||||
case 'f': case 'g': case 'h': case 'i': case 'j':
|
||||
case 'k': case 'l': case 'm': case 'n': case 'o':
|
||||
case 'p': case 'q': case 'r': case 's': case 't':
|
||||
case 'u': case 'v': case 'w': case 'x': case 'y':
|
||||
case 'z':
|
||||
case '$': case '_':
|
||||
case '0': case '1': case '2': case '3': case '4':
|
||||
case '5': case '6': case '7': case '8': case '9':
|
||||
case '\u0000': case '\u0001': case '\u0002': case '\u0003':
|
||||
case '\u0004': case '\u0005': case '\u0006': case '\u0007':
|
||||
case '\u0008': case '\u000E': case '\u000F': case '\u0010':
|
||||
case '\u0011': case '\u0012': case '\u0013': case '\u0014':
|
||||
case '\u0015': case '\u0016': case '\u0017':
|
||||
case '\u0018': case '\u0019': case '\u001B':
|
||||
case '\u007F':
|
||||
break;
|
||||
case '\u001A': // EOI is also a legal identifier part
|
||||
if (reader.bp >= reader.buflen) {
|
||||
name = names.fromChars(sbuf, 0, sp);
|
||||
tk = tokens.lookupKind(name);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if (reader.ch < '\u0080') {
|
||||
// all ASCII range chars already handled, above
|
||||
isJavaIdentifierPart = false;
|
||||
} else {
|
||||
high = reader.scanSurrogates();
|
||||
if (high != 0) {
|
||||
if (sp == sbuf.length) {
|
||||
putChar(high);
|
||||
} else {
|
||||
sbuf[sp++] = high;
|
||||
}
|
||||
isJavaIdentifierPart = Character.isJavaIdentifierPart(
|
||||
Character.toCodePoint(high, reader.ch));
|
||||
} else {
|
||||
isJavaIdentifierPart = Character.isJavaIdentifierPart(reader.ch);
|
||||
}
|
||||
}
|
||||
if (!isJavaIdentifierPart) {
|
||||
name = names.fromChars(sbuf, 0, sp);
|
||||
tk = tokens.lookupKind(name);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} while (true);
|
||||
}
|
||||
|
||||
/** Return true if reader.ch can be part of an operator.
|
||||
*/
|
||||
private boolean isSpecial(char ch) {
|
||||
switch (ch) {
|
||||
case '!': case '%': case '&': case '*': case '?':
|
||||
case '+': case '-': case ':': case '<': case '=':
|
||||
case '>': case '^': case '|': case '~':
|
||||
case '@':
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Read longest possible sequence of special characters and convert
|
||||
* to token.
|
||||
*/
|
||||
private void scanOperator() {
|
||||
while (true) {
|
||||
putChar(reader.ch);
|
||||
Name newname = names.fromChars(sbuf, 0, sp);
|
||||
TokenKind tk1 = tokens.lookupKind(newname);
|
||||
if (tk1 == TokenKind.IDENTIFIER) {
|
||||
sp--;
|
||||
break;
|
||||
}
|
||||
tk = tk1;
|
||||
reader.scanChar();
|
||||
if (!isSpecial(reader.ch)) break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan a documentation comment; determine if a deprecated tag is present.
|
||||
* Called once the initial /, * have been skipped, positioned at the second *
|
||||
* (which is treated as the beginning of the first line).
|
||||
* Stops positioned at the closing '/'.
|
||||
*/
|
||||
@SuppressWarnings("fallthrough")
|
||||
private void scanDocComment() {
|
||||
boolean deprecatedPrefix = false;
|
||||
|
||||
forEachLine:
|
||||
while (reader.bp < reader.buflen) {
|
||||
|
||||
// Skip optional WhiteSpace at beginning of line
|
||||
while (reader.bp < reader.buflen && (reader.ch == ' ' || reader.ch == '\t' || reader.ch == FF)) {
|
||||
scanCommentChar();
|
||||
}
|
||||
|
||||
// Skip optional consecutive Stars
|
||||
while (reader.bp < reader.buflen && reader.ch == '*') {
|
||||
scanCommentChar();
|
||||
if (reader.ch == '/') {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip optional WhiteSpace after Stars
|
||||
while (reader.bp < reader.buflen && (reader.ch == ' ' || reader.ch == '\t' || reader.ch == FF)) {
|
||||
scanCommentChar();
|
||||
}
|
||||
|
||||
deprecatedPrefix = false;
|
||||
// At beginning of line in the JavaDoc sense.
|
||||
if (reader.bp < reader.buflen && reader.ch == '@' && !deprecatedFlag) {
|
||||
scanCommentChar();
|
||||
if (reader.bp < reader.buflen && reader.ch == 'd') {
|
||||
scanCommentChar();
|
||||
if (reader.bp < reader.buflen && reader.ch == 'e') {
|
||||
scanCommentChar();
|
||||
if (reader.bp < reader.buflen && reader.ch == 'p') {
|
||||
scanCommentChar();
|
||||
if (reader.bp < reader.buflen && reader.ch == 'r') {
|
||||
scanCommentChar();
|
||||
if (reader.bp < reader.buflen && reader.ch == 'e') {
|
||||
scanCommentChar();
|
||||
if (reader.bp < reader.buflen && reader.ch == 'c') {
|
||||
scanCommentChar();
|
||||
if (reader.bp < reader.buflen && reader.ch == 'a') {
|
||||
scanCommentChar();
|
||||
if (reader.bp < reader.buflen && reader.ch == 't') {
|
||||
scanCommentChar();
|
||||
if (reader.bp < reader.buflen && reader.ch == 'e') {
|
||||
scanCommentChar();
|
||||
if (reader.bp < reader.buflen && reader.ch == 'd') {
|
||||
deprecatedPrefix = true;
|
||||
scanCommentChar();
|
||||
}}}}}}}}}}}
|
||||
if (deprecatedPrefix && reader.bp < reader.buflen) {
|
||||
if (Character.isWhitespace(reader.ch)) {
|
||||
deprecatedFlag = true;
|
||||
} else if (reader.ch == '*') {
|
||||
scanCommentChar();
|
||||
if (reader.ch == '/') {
|
||||
deprecatedFlag = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Skip rest of line
|
||||
while (reader.bp < reader.buflen) {
|
||||
switch (reader.ch) {
|
||||
case '*':
|
||||
scanCommentChar();
|
||||
if (reader.ch == '/') {
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case CR: // (Spec 3.4)
|
||||
scanCommentChar();
|
||||
if (reader.ch != LF) {
|
||||
continue forEachLine;
|
||||
}
|
||||
/* fall through to LF case */
|
||||
case LF: // (Spec 3.4)
|
||||
scanCommentChar();
|
||||
continue forEachLine;
|
||||
default:
|
||||
scanCommentChar();
|
||||
}
|
||||
} // rest of line
|
||||
} // forEachLine
|
||||
return;
|
||||
}
|
||||
|
||||
/** Read token.
|
||||
*/
|
||||
public Token readToken() {
|
||||
|
||||
sp = 0;
|
||||
name = null;
|
||||
deprecatedFlag = false;
|
||||
radix = 0;
|
||||
int pos = 0;
|
||||
int endPos = 0;
|
||||
|
||||
try {
|
||||
loop: while (true) {
|
||||
pos = reader.bp;
|
||||
switch (reader.ch) {
|
||||
case ' ': // (Spec 3.6)
|
||||
case '\t': // (Spec 3.6)
|
||||
case FF: // (Spec 3.6)
|
||||
do {
|
||||
reader.scanChar();
|
||||
} while (reader.ch == ' ' || reader.ch == '\t' || reader.ch == FF);
|
||||
processWhiteSpace(pos, reader.bp);
|
||||
break;
|
||||
case LF: // (Spec 3.4)
|
||||
reader.scanChar();
|
||||
processLineTerminator(pos, reader.bp);
|
||||
break;
|
||||
case CR: // (Spec 3.4)
|
||||
reader.scanChar();
|
||||
if (reader.ch == LF) {
|
||||
reader.scanChar();
|
||||
}
|
||||
processLineTerminator(pos, reader.bp);
|
||||
break;
|
||||
case 'A': case 'B': case 'C': case 'D': case 'E':
|
||||
case 'F': case 'G': case 'H': case 'I': case 'J':
|
||||
case 'K': case 'L': case 'M': case 'N': case 'O':
|
||||
case 'P': case 'Q': case 'R': case 'S': case 'T':
|
||||
case 'U': case 'V': case 'W': case 'X': case 'Y':
|
||||
case 'Z':
|
||||
case 'a': case 'b': case 'c': case 'd': case 'e':
|
||||
case 'f': case 'g': case 'h': case 'i': case 'j':
|
||||
case 'k': case 'l': case 'm': case 'n': case 'o':
|
||||
case 'p': case 'q': case 'r': case 's': case 't':
|
||||
case 'u': case 'v': case 'w': case 'x': case 'y':
|
||||
case 'z':
|
||||
case '$': case '_':
|
||||
scanIdent();
|
||||
break loop;
|
||||
case '0':
|
||||
reader.scanChar();
|
||||
if (reader.ch == 'x' || reader.ch == 'X') {
|
||||
reader.scanChar();
|
||||
skipIllegalUnderscores();
|
||||
if (reader.ch == '.') {
|
||||
scanHexFractionAndSuffix(pos, false);
|
||||
} else if (reader.digit(pos, 16) < 0) {
|
||||
lexError(pos, "invalid.hex.number");
|
||||
} else {
|
||||
scanNumber(pos, 16);
|
||||
}
|
||||
} else if (reader.ch == 'b' || reader.ch == 'B') {
|
||||
if (!allowBinaryLiterals) {
|
||||
lexError(pos, "unsupported.binary.lit", source.name);
|
||||
allowBinaryLiterals = true;
|
||||
}
|
||||
reader.scanChar();
|
||||
skipIllegalUnderscores();
|
||||
if (reader.digit(pos, 2) < 0) {
|
||||
lexError(pos, "invalid.binary.number");
|
||||
} else {
|
||||
scanNumber(pos, 2);
|
||||
}
|
||||
} else {
|
||||
putChar('0');
|
||||
if (reader.ch == '_') {
|
||||
int savePos = reader.bp;
|
||||
do {
|
||||
reader.scanChar();
|
||||
} while (reader.ch == '_');
|
||||
if (reader.digit(pos, 10) < 0) {
|
||||
lexError(savePos, "illegal.underscore");
|
||||
}
|
||||
}
|
||||
scanNumber(pos, 8);
|
||||
}
|
||||
break loop;
|
||||
case '1': case '2': case '3': case '4':
|
||||
case '5': case '6': case '7': case '8': case '9':
|
||||
scanNumber(pos, 10);
|
||||
break loop;
|
||||
case '.':
|
||||
reader.scanChar();
|
||||
if ('0' <= reader.ch && reader.ch <= '9') {
|
||||
putChar('.');
|
||||
scanFractionAndSuffix(pos);
|
||||
} else if (reader.ch == '.') {
|
||||
putChar('.'); putChar('.');
|
||||
reader.scanChar();
|
||||
if (reader.ch == '.') {
|
||||
reader.scanChar();
|
||||
putChar('.');
|
||||
tk = TokenKind.ELLIPSIS;
|
||||
} else {
|
||||
lexError(pos, "malformed.fp.lit");
|
||||
}
|
||||
} else {
|
||||
tk = TokenKind.DOT;
|
||||
}
|
||||
break loop;
|
||||
case ',':
|
||||
reader.scanChar(); tk = TokenKind.COMMA; break loop;
|
||||
case ';':
|
||||
reader.scanChar(); tk = TokenKind.SEMI; break loop;
|
||||
case '(':
|
||||
reader.scanChar(); tk = TokenKind.LPAREN; break loop;
|
||||
case ')':
|
||||
reader.scanChar(); tk = TokenKind.RPAREN; break loop;
|
||||
case '[':
|
||||
reader.scanChar(); tk = TokenKind.LBRACKET; break loop;
|
||||
case ']':
|
||||
reader.scanChar(); tk = TokenKind.RBRACKET; break loop;
|
||||
case '{':
|
||||
reader.scanChar(); tk = TokenKind.LBRACE; break loop;
|
||||
case '}':
|
||||
reader.scanChar(); tk = TokenKind.RBRACE; break loop;
|
||||
case '/':
|
||||
reader.scanChar();
|
||||
if (reader.ch == '/') {
|
||||
do {
|
||||
scanCommentChar();
|
||||
} while (reader.ch != CR && reader.ch != LF && reader.bp < reader.buflen);
|
||||
if (reader.bp < reader.buflen) {
|
||||
processComment(pos, reader.bp, CommentStyle.LINE);
|
||||
}
|
||||
break;
|
||||
} else if (reader.ch == '*') {
|
||||
reader.scanChar();
|
||||
CommentStyle style;
|
||||
if (reader.ch == '*') {
|
||||
style = CommentStyle.JAVADOC;
|
||||
scanDocComment();
|
||||
} else {
|
||||
style = CommentStyle.BLOCK;
|
||||
while (reader.bp < reader.buflen) {
|
||||
if (reader.ch == '*') {
|
||||
reader.scanChar();
|
||||
if (reader.ch == '/') break;
|
||||
} else {
|
||||
scanCommentChar();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (reader.ch == '/') {
|
||||
reader.scanChar();
|
||||
processComment(pos, reader.bp, style);
|
||||
break;
|
||||
} else {
|
||||
lexError(pos, "unclosed.comment");
|
||||
break loop;
|
||||
}
|
||||
} else if (reader.ch == '=') {
|
||||
tk = TokenKind.SLASHEQ;
|
||||
reader.scanChar();
|
||||
} else {
|
||||
tk = TokenKind.SLASH;
|
||||
}
|
||||
break loop;
|
||||
case '\'':
|
||||
reader.scanChar();
|
||||
if (reader.ch == '\'') {
|
||||
lexError(pos, "empty.char.lit");
|
||||
} else {
|
||||
if (reader.ch == CR || reader.ch == LF)
|
||||
lexError(pos, "illegal.line.end.in.char.lit");
|
||||
scanLitChar(pos);
|
||||
char ch2 = reader.ch;
|
||||
if (reader.ch == '\'') {
|
||||
reader.scanChar();
|
||||
tk = TokenKind.CHARLITERAL;
|
||||
} else {
|
||||
lexError(pos, "unclosed.char.lit");
|
||||
}
|
||||
}
|
||||
break loop;
|
||||
case '\"':
|
||||
reader.scanChar();
|
||||
while (reader.ch != '\"' && reader.ch != CR && reader.ch != LF && reader.bp < reader.buflen)
|
||||
scanLitChar(pos);
|
||||
if (reader.ch == '\"') {
|
||||
tk = TokenKind.STRINGLITERAL;
|
||||
reader.scanChar();
|
||||
} else {
|
||||
lexError(pos, "unclosed.str.lit");
|
||||
}
|
||||
break loop;
|
||||
default:
|
||||
if (isSpecial(reader.ch)) {
|
||||
scanOperator();
|
||||
} else {
|
||||
boolean isJavaIdentifierStart;
|
||||
if (reader.ch < '\u0080') {
|
||||
// all ASCII range chars already handled, above
|
||||
isJavaIdentifierStart = false;
|
||||
} else {
|
||||
char high = reader.scanSurrogates();
|
||||
if (high != 0) {
|
||||
if (sp == sbuf.length) {
|
||||
putChar(high);
|
||||
} else {
|
||||
sbuf[sp++] = high;
|
||||
}
|
||||
|
||||
isJavaIdentifierStart = Character.isJavaIdentifierStart(
|
||||
Character.toCodePoint(high, reader.ch));
|
||||
} else {
|
||||
isJavaIdentifierStart = Character.isJavaIdentifierStart(reader.ch);
|
||||
}
|
||||
}
|
||||
if (isJavaIdentifierStart) {
|
||||
scanIdent();
|
||||
} else if (reader.bp == reader.buflen || reader.ch == EOI && reader.bp + 1 == reader.buflen) { // JLS 3.5
|
||||
tk = TokenKind.EOF;
|
||||
pos = reader.buflen;
|
||||
} else {
|
||||
lexError(pos, "illegal.char", String.valueOf((int)reader.ch));
|
||||
reader.scanChar();
|
||||
}
|
||||
}
|
||||
break loop;
|
||||
}
|
||||
}
|
||||
endPos = reader.bp;
|
||||
switch (tk.tag) {
|
||||
case DEFAULT: return new Token(tk, pos, endPos, deprecatedFlag);
|
||||
case NAMED: return new NamedToken(tk, pos, endPos, name, deprecatedFlag);
|
||||
case STRING: return new StringToken(tk, pos, endPos, new String(sbuf, 0, sp), deprecatedFlag);
|
||||
case NUMERIC: return new NumericToken(tk, pos, endPos, new String(sbuf, 0, sp), radix, deprecatedFlag);
|
||||
default: throw new AssertionError();
|
||||
}
|
||||
}
|
||||
finally {
|
||||
if (scannerDebug) {
|
||||
System.out.println("nextToken(" + pos
|
||||
+ "," + endPos + ")=|" +
|
||||
new String(reader.getRawCharacters(pos, endPos))
|
||||
+ "|");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Return the position where a lexical error occurred;
|
||||
*/
|
||||
public int errPos() {
|
||||
return errPos;
|
||||
}
|
||||
|
||||
/** Set the position where a lexical error occurred;
|
||||
*/
|
||||
public void errPos(int pos) {
|
||||
errPos = pos;
|
||||
}
|
||||
|
||||
public enum CommentStyle {
|
||||
LINE,
|
||||
BLOCK,
|
||||
JAVADOC,
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a complete comment has been scanned. pos and endPos
|
||||
* will mark the comment boundary.
|
||||
*/
|
||||
protected void processComment(int pos, int endPos, CommentStyle style) {
|
||||
if (scannerDebug)
|
||||
System.out.println("processComment(" + pos
|
||||
+ "," + endPos + "," + style + ")=|"
|
||||
+ new String(reader.getRawCharacters(pos, endPos))
|
||||
+ "|");
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a complete whitespace run has been scanned. pos and endPos
|
||||
* will mark the whitespace boundary.
|
||||
*/
|
||||
protected void processWhiteSpace(int pos, int endPos) {
|
||||
if (scannerDebug)
|
||||
System.out.println("processWhitespace(" + pos
|
||||
+ "," + endPos + ")=|" +
|
||||
new String(reader.getRawCharacters(pos, endPos))
|
||||
+ "|");
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a line terminator has been processed.
|
||||
*/
|
||||
protected void processLineTerminator(int pos, int endPos) {
|
||||
if (scannerDebug)
|
||||
System.out.println("processTerminator(" + pos
|
||||
+ "," + endPos + ")=|" +
|
||||
new String(reader.getRawCharacters(pos, endPos))
|
||||
+ "|");
|
||||
}
|
||||
|
||||
/** Build a map for translating between line numbers and
|
||||
* positions in the input.
|
||||
*
|
||||
* @return a LineMap */
|
||||
public Position.LineMap getLineMap() {
|
||||
return Position.makeLineMap(reader.getRawCharacters(), reader.buflen, false);
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
|
||||
* Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
@ -25,9 +25,12 @@
|
||||
|
||||
package com.sun.tools.javac.parser;
|
||||
|
||||
import com.sun.tools.javac.file.JavacFileManager;
|
||||
import com.sun.tools.javac.parser.Tokens.Token;
|
||||
import com.sun.tools.javac.util.*;
|
||||
|
||||
import java.nio.*;
|
||||
|
||||
import com.sun.tools.javac.util.*;
|
||||
import static com.sun.tools.javac.util.LayoutCharacters.*;
|
||||
|
||||
/** An extension to the base lexical analyzer that captures
|
||||
@ -40,26 +43,22 @@ import static com.sun.tools.javac.util.LayoutCharacters.*;
|
||||
* This code and its internal interfaces are subject to change or
|
||||
* deletion without notice.</b>
|
||||
*/
|
||||
public class DocCommentScanner extends Scanner {
|
||||
public class JavadocTokenizer extends JavaTokenizer {
|
||||
|
||||
/** Create a scanner from the input buffer. buffer must implement
|
||||
* array() and compact(), and remaining() must be less than limit().
|
||||
*/
|
||||
protected DocCommentScanner(ScannerFactory fac, CharBuffer buffer) {
|
||||
protected JavadocTokenizer(ScannerFactory fac, CharBuffer buffer) {
|
||||
super(fac, buffer);
|
||||
}
|
||||
|
||||
/** Create a scanner from the input array. The array must have at
|
||||
* least a single character of extra space.
|
||||
*/
|
||||
protected DocCommentScanner(ScannerFactory fac, char[] input, int inputLength) {
|
||||
protected JavadocTokenizer(ScannerFactory fac, char[] input, int inputLength) {
|
||||
super(fac, input, inputLength);
|
||||
}
|
||||
|
||||
/** Starting position of the comment in original source
|
||||
*/
|
||||
private int pos;
|
||||
|
||||
/** The comment input buffer, index of next chacter to be read,
|
||||
* index of one past last character in buffer.
|
||||
*/
|
||||
@ -178,6 +177,14 @@ public class DocCommentScanner extends Scanner {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Token readToken() {
|
||||
docComment = null;
|
||||
Token tk = super.readToken();
|
||||
tk.docComment = docComment;
|
||||
return tk;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read next character in doc comment, skipping over double '\' characters.
|
||||
* If a double '\' is skipped, put in the buffer and update buffer count.
|
||||
@ -196,32 +203,17 @@ public class DocCommentScanner extends Scanner {
|
||||
}
|
||||
}
|
||||
|
||||
/* Reset doc comment before reading each new token
|
||||
*/
|
||||
public void nextToken() {
|
||||
docComment = null;
|
||||
super.nextToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the documentation string of the current token.
|
||||
*/
|
||||
public String docComment() {
|
||||
return docComment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a doc comment and make the string content available.
|
||||
* Strips leading whitespace and stars.
|
||||
*/
|
||||
@SuppressWarnings("fallthrough")
|
||||
protected void processComment(CommentStyle style) {
|
||||
protected void processComment(int pos, int endPos, CommentStyle style) {
|
||||
if (style != CommentStyle.JAVADOC) {
|
||||
return;
|
||||
}
|
||||
|
||||
pos = pos();
|
||||
buf = getRawCharacters(pos, endPos());
|
||||
buf = reader.getRawCharacters(pos, endPos);
|
||||
buflen = buf.length;
|
||||
bp = 0;
|
||||
col = 0;
|
||||
@ -414,7 +406,7 @@ public class DocCommentScanner extends Scanner {
|
||||
*
|
||||
* @return a LineMap */
|
||||
public Position.LineMap getLineMap() {
|
||||
char[] buf = getRawCharacters();
|
||||
char[] buf = reader.getRawCharacters();
|
||||
return Position.makeLineMap(buf, buf.length, true);
|
||||
}
|
||||
}
|
@ -1,98 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package com.sun.tools.javac.parser;
|
||||
|
||||
import com.sun.tools.javac.util.Context;
|
||||
import com.sun.tools.javac.util.Log;
|
||||
import com.sun.tools.javac.util.Name;
|
||||
import com.sun.tools.javac.util.Names;
|
||||
|
||||
import static com.sun.tools.javac.parser.Token.*;
|
||||
|
||||
/**
|
||||
* Map from Name to Token and Token to String.
|
||||
*
|
||||
* <p><b>This is NOT part of any supported API.
|
||||
* If you write code that depends on this, you do so at your own risk.
|
||||
* This code and its internal interfaces are subject to change or
|
||||
* deletion without notice.</b>
|
||||
*/
|
||||
public class Keywords {
|
||||
public static final Context.Key<Keywords> keywordsKey =
|
||||
new Context.Key<Keywords>();
|
||||
|
||||
public static Keywords instance(Context context) {
|
||||
Keywords instance = context.get(keywordsKey);
|
||||
if (instance == null)
|
||||
instance = new Keywords(context);
|
||||
return instance;
|
||||
}
|
||||
|
||||
private final Names names;
|
||||
|
||||
protected Keywords(Context context) {
|
||||
context.put(keywordsKey, this);
|
||||
names = Names.instance(context);
|
||||
|
||||
for (Token t : Token.values()) {
|
||||
if (t.name != null)
|
||||
enterKeyword(t.name, t);
|
||||
else
|
||||
tokenName[t.ordinal()] = null;
|
||||
}
|
||||
|
||||
key = new Token[maxKey+1];
|
||||
for (int i = 0; i <= maxKey; i++) key[i] = IDENTIFIER;
|
||||
for (Token t : Token.values()) {
|
||||
if (t.name != null)
|
||||
key[tokenName[t.ordinal()].getIndex()] = t;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Token key(Name name) {
|
||||
return (name.getIndex() > maxKey) ? IDENTIFIER : key[name.getIndex()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyword array. Maps name indices to Token.
|
||||
*/
|
||||
private final Token[] key;
|
||||
|
||||
/** The number of the last entered keyword.
|
||||
*/
|
||||
private int maxKey = 0;
|
||||
|
||||
/** The names of all tokens.
|
||||
*/
|
||||
private Name[] tokenName = new Name[Token.values().length];
|
||||
|
||||
private void enterKeyword(String s, Token token) {
|
||||
Name n = names.fromString(s);
|
||||
tokenName[token.ordinal()] = n;
|
||||
if (n.getIndex() > maxKey) maxKey = n.getIndex();
|
||||
}
|
||||
}
|
@ -25,7 +25,7 @@
|
||||
|
||||
package com.sun.tools.javac.parser;
|
||||
|
||||
import com.sun.tools.javac.util.*;
|
||||
import com.sun.tools.javac.parser.Tokens.*;
|
||||
import com.sun.tools.javac.util.Position.LineMap;
|
||||
|
||||
/**
|
||||
@ -40,22 +40,26 @@ import com.sun.tools.javac.util.Position.LineMap;
|
||||
public interface Lexer {
|
||||
|
||||
/**
|
||||
* Has a @deprecated been encountered in last doc comment?
|
||||
* This needs to be reset by client with resetDeprecatedFlag.
|
||||
* Consume the next token.
|
||||
*/
|
||||
boolean deprecatedFlag();
|
||||
|
||||
void resetDeprecatedFlag();
|
||||
void nextToken();
|
||||
|
||||
/**
|
||||
* Returns the documentation string of the current token.
|
||||
* Return current token.
|
||||
*/
|
||||
String docComment();
|
||||
Token token();
|
||||
|
||||
/**
|
||||
* Return the last character position of the current token.
|
||||
* Return the last character position of the previous token.
|
||||
*/
|
||||
int endPos();
|
||||
Token prevToken();
|
||||
|
||||
/**
|
||||
* Splits the current token in two and return the first (splitted) token.
|
||||
* For instance '<<<' is splitted into two tokens '<' and '<<' respectively,
|
||||
* and the latter is returned.
|
||||
*/
|
||||
Token split();
|
||||
|
||||
/**
|
||||
* Return the position where a lexical error occurred;
|
||||
@ -74,69 +78,4 @@ public interface Lexer {
|
||||
* @return a LineMap
|
||||
*/
|
||||
LineMap getLineMap();
|
||||
|
||||
/**
|
||||
* Returns a copy of the input buffer, up to its inputLength.
|
||||
* Unicode escape sequences are not translated.
|
||||
*/
|
||||
char[] getRawCharacters();
|
||||
|
||||
/**
|
||||
* Returns a copy of a character array subset of the input buffer.
|
||||
* The returned array begins at the <code>beginIndex</code> and
|
||||
* extends to the character at index <code>endIndex - 1</code>.
|
||||
* Thus the length of the substring is <code>endIndex-beginIndex</code>.
|
||||
* This behavior is like
|
||||
* <code>String.substring(beginIndex, endIndex)</code>.
|
||||
* Unicode escape sequences are not translated.
|
||||
*
|
||||
* @param beginIndex the beginning index, inclusive.
|
||||
* @param endIndex the ending index, exclusive.
|
||||
* @throws IndexOutOfBounds if either offset is outside of the
|
||||
* array bounds
|
||||
*/
|
||||
char[] getRawCharacters(int beginIndex, int endIndex);
|
||||
|
||||
/**
|
||||
* Return the name of an identifier or token for the current token.
|
||||
*/
|
||||
Name name();
|
||||
|
||||
/**
|
||||
* Read token.
|
||||
*/
|
||||
void nextToken();
|
||||
|
||||
/**
|
||||
* Return the current token's position: a 0-based
|
||||
* offset from beginning of the raw input stream
|
||||
* (before unicode translation)
|
||||
*/
|
||||
int pos();
|
||||
|
||||
/**
|
||||
* Return the last character position of the previous token.
|
||||
*/
|
||||
int prevEndPos();
|
||||
|
||||
/**
|
||||
* Return the radix of a numeric literal token.
|
||||
*/
|
||||
int radix();
|
||||
|
||||
/**
|
||||
* The value of a literal token, recorded as a string.
|
||||
* For integers, leading 0x and 'l' suffixes are suppressed.
|
||||
*/
|
||||
String stringVal();
|
||||
|
||||
/**
|
||||
* Return the current token, set by nextToken().
|
||||
*/
|
||||
Token token();
|
||||
|
||||
/**
|
||||
* Sets the current token.
|
||||
*/
|
||||
void token(Token token);
|
||||
}
|
||||
|
@ -55,7 +55,7 @@ public class ParserFactory {
|
||||
|
||||
final TreeMaker F;
|
||||
final Log log;
|
||||
final Keywords keywords;
|
||||
final Tokens tokens;
|
||||
final Source source;
|
||||
final Names names;
|
||||
final Options options;
|
||||
@ -67,7 +67,7 @@ public class ParserFactory {
|
||||
this.F = TreeMaker.instance(context);
|
||||
this.log = Log.instance(context);
|
||||
this.names = Names.instance(context);
|
||||
this.keywords = Keywords.instance(context);
|
||||
this.tokens = Tokens.instance(context);
|
||||
this.source = Source.instance(context);
|
||||
this.options = Options.instance(context);
|
||||
this.scannerFactory = ScannerFactory.instance(context);
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -57,7 +57,7 @@ public class ScannerFactory {
|
||||
final Log log;
|
||||
final Names names;
|
||||
final Source source;
|
||||
final Keywords keywords;
|
||||
final Tokens tokens;
|
||||
|
||||
/** Create a new scanner factory. */
|
||||
protected ScannerFactory(Context context) {
|
||||
@ -65,14 +65,14 @@ public class ScannerFactory {
|
||||
this.log = Log.instance(context);
|
||||
this.names = Names.instance(context);
|
||||
this.source = Source.instance(context);
|
||||
this.keywords = Keywords.instance(context);
|
||||
this.tokens = Tokens.instance(context);
|
||||
}
|
||||
|
||||
public Scanner newScanner(CharSequence input, boolean keepDocComments) {
|
||||
if (input instanceof CharBuffer) {
|
||||
CharBuffer buf = (CharBuffer) input;
|
||||
if (keepDocComments)
|
||||
return new DocCommentScanner(this, buf);
|
||||
return new Scanner(this, new JavadocTokenizer(this, buf));
|
||||
else
|
||||
return new Scanner(this, buf);
|
||||
} else {
|
||||
@ -83,7 +83,7 @@ public class ScannerFactory {
|
||||
|
||||
public Scanner newScanner(char[] input, int inputLength, boolean keepDocComments) {
|
||||
if (keepDocComments)
|
||||
return new DocCommentScanner(this, input, inputLength);
|
||||
return new Scanner(this, new JavadocTokenizer(this, input, inputLength));
|
||||
else
|
||||
return new Scanner(this, input, inputLength);
|
||||
}
|
||||
|
@ -1,198 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package com.sun.tools.javac.parser;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import com.sun.tools.javac.api.Formattable;
|
||||
import com.sun.tools.javac.api.Messages;
|
||||
|
||||
/** An interface that defines codes for Java source tokens
|
||||
* returned from lexical analysis.
|
||||
*
|
||||
* <p><b>This is NOT part of any supported API.
|
||||
* If you write code that depends on this, you do so at your own risk.
|
||||
* This code and its internal interfaces are subject to change or
|
||||
* deletion without notice.</b>
|
||||
*/
|
||||
public enum Token implements Formattable {
|
||||
EOF,
|
||||
ERROR,
|
||||
IDENTIFIER,
|
||||
ABSTRACT("abstract"),
|
||||
ASSERT("assert"),
|
||||
BOOLEAN("boolean"),
|
||||
BREAK("break"),
|
||||
BYTE("byte"),
|
||||
CASE("case"),
|
||||
CATCH("catch"),
|
||||
CHAR("char"),
|
||||
CLASS("class"),
|
||||
CONST("const"),
|
||||
CONTINUE("continue"),
|
||||
DEFAULT("default"),
|
||||
DO("do"),
|
||||
DOUBLE("double"),
|
||||
ELSE("else"),
|
||||
ENUM("enum"),
|
||||
EXTENDS("extends"),
|
||||
FINAL("final"),
|
||||
FINALLY("finally"),
|
||||
FLOAT("float"),
|
||||
FOR("for"),
|
||||
GOTO("goto"),
|
||||
IF("if"),
|
||||
IMPLEMENTS("implements"),
|
||||
IMPORT("import"),
|
||||
INSTANCEOF("instanceof"),
|
||||
INT("int"),
|
||||
INTERFACE("interface"),
|
||||
LONG("long"),
|
||||
NATIVE("native"),
|
||||
NEW("new"),
|
||||
PACKAGE("package"),
|
||||
PRIVATE("private"),
|
||||
PROTECTED("protected"),
|
||||
PUBLIC("public"),
|
||||
RETURN("return"),
|
||||
SHORT("short"),
|
||||
STATIC("static"),
|
||||
STRICTFP("strictfp"),
|
||||
SUPER("super"),
|
||||
SWITCH("switch"),
|
||||
SYNCHRONIZED("synchronized"),
|
||||
THIS("this"),
|
||||
THROW("throw"),
|
||||
THROWS("throws"),
|
||||
TRANSIENT("transient"),
|
||||
TRY("try"),
|
||||
VOID("void"),
|
||||
VOLATILE("volatile"),
|
||||
WHILE("while"),
|
||||
INTLITERAL,
|
||||
LONGLITERAL,
|
||||
FLOATLITERAL,
|
||||
DOUBLELITERAL,
|
||||
CHARLITERAL,
|
||||
STRINGLITERAL,
|
||||
TRUE("true"),
|
||||
FALSE("false"),
|
||||
NULL("null"),
|
||||
LPAREN("("),
|
||||
RPAREN(")"),
|
||||
LBRACE("{"),
|
||||
RBRACE("}"),
|
||||
LBRACKET("["),
|
||||
RBRACKET("]"),
|
||||
SEMI(";"),
|
||||
COMMA(","),
|
||||
DOT("."),
|
||||
ELLIPSIS("..."),
|
||||
EQ("="),
|
||||
GT(">"),
|
||||
LT("<"),
|
||||
BANG("!"),
|
||||
TILDE("~"),
|
||||
QUES("?"),
|
||||
COLON(":"),
|
||||
EQEQ("=="),
|
||||
LTEQ("<="),
|
||||
GTEQ(">="),
|
||||
BANGEQ("!="),
|
||||
AMPAMP("&&"),
|
||||
BARBAR("||"),
|
||||
PLUSPLUS("++"),
|
||||
SUBSUB("--"),
|
||||
PLUS("+"),
|
||||
SUB("-"),
|
||||
STAR("*"),
|
||||
SLASH("/"),
|
||||
AMP("&"),
|
||||
BAR("|"),
|
||||
CARET("^"),
|
||||
PERCENT("%"),
|
||||
LTLT("<<"),
|
||||
GTGT(">>"),
|
||||
GTGTGT(">>>"),
|
||||
PLUSEQ("+="),
|
||||
SUBEQ("-="),
|
||||
STAREQ("*="),
|
||||
SLASHEQ("/="),
|
||||
AMPEQ("&="),
|
||||
BAREQ("|="),
|
||||
CARETEQ("^="),
|
||||
PERCENTEQ("%="),
|
||||
LTLTEQ("<<="),
|
||||
GTGTEQ(">>="),
|
||||
GTGTGTEQ(">>>="),
|
||||
MONKEYS_AT("@"),
|
||||
CUSTOM;
|
||||
|
||||
Token() {
|
||||
this(null);
|
||||
}
|
||||
Token(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public final String name;
|
||||
|
||||
public String toString() {
|
||||
switch (this) {
|
||||
case IDENTIFIER:
|
||||
return "token.identifier";
|
||||
case CHARLITERAL:
|
||||
return "token.character";
|
||||
case STRINGLITERAL:
|
||||
return "token.string";
|
||||
case INTLITERAL:
|
||||
return "token.integer";
|
||||
case LONGLITERAL:
|
||||
return "token.long-integer";
|
||||
case FLOATLITERAL:
|
||||
return "token.float";
|
||||
case DOUBLELITERAL:
|
||||
return "token.double";
|
||||
case ERROR:
|
||||
return "token.bad-symbol";
|
||||
case EOF:
|
||||
return "token.end-of-input";
|
||||
case DOT: case COMMA: case SEMI: case LPAREN: case RPAREN:
|
||||
case LBRACKET: case RBRACKET: case LBRACE: case RBRACE:
|
||||
return "'" + name + "'";
|
||||
default:
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
public String getKind() {
|
||||
return "Token";
|
||||
}
|
||||
|
||||
public String toString(Locale locale, Messages messages) {
|
||||
return name != null ? toString() : messages.getLocalizedString(locale, "compiler.misc." + toString());
|
||||
}
|
||||
}
|
@ -0,0 +1,423 @@
|
||||
/*
|
||||
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package com.sun.tools.javac.parser;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import com.sun.tools.javac.api.Formattable;
|
||||
import com.sun.tools.javac.api.Messages;
|
||||
import com.sun.tools.javac.parser.Tokens.Token.Tag;
|
||||
import com.sun.tools.javac.util.Name;
|
||||
import com.sun.tools.javac.util.Context;
|
||||
import com.sun.tools.javac.util.Names;
|
||||
|
||||
/** A class that defines codes/utilities for Java source tokens
|
||||
* returned from lexical analysis.
|
||||
*
|
||||
* <p><b>This is NOT part of any supported API.
|
||||
* If you write code that depends on this, you do so at your own risk.
|
||||
* This code and its internal interfaces are subject to change or
|
||||
* deletion without notice.</b>
|
||||
*/
|
||||
public class Tokens {
|
||||
|
||||
private final Names names;
|
||||
|
||||
/**
|
||||
* Keyword array. Maps name indices to Token.
|
||||
*/
|
||||
private final TokenKind[] key;
|
||||
|
||||
/** The number of the last entered keyword.
|
||||
*/
|
||||
private int maxKey = 0;
|
||||
|
||||
/** The names of all tokens.
|
||||
*/
|
||||
private Name[] tokenName = new Name[TokenKind.values().length];
|
||||
|
||||
public static final Context.Key<Tokens> tokensKey =
|
||||
new Context.Key<Tokens>();
|
||||
|
||||
public static Tokens instance(Context context) {
|
||||
Tokens instance = context.get(tokensKey);
|
||||
if (instance == null)
|
||||
instance = new Tokens(context);
|
||||
return instance;
|
||||
}
|
||||
|
||||
protected Tokens(Context context) {
|
||||
context.put(tokensKey, this);
|
||||
names = Names.instance(context);
|
||||
|
||||
for (TokenKind t : TokenKind.values()) {
|
||||
if (t.name != null)
|
||||
enterKeyword(t.name, t);
|
||||
else
|
||||
tokenName[t.ordinal()] = null;
|
||||
}
|
||||
|
||||
key = new TokenKind[maxKey+1];
|
||||
for (int i = 0; i <= maxKey; i++) key[i] = TokenKind.IDENTIFIER;
|
||||
for (TokenKind t : TokenKind.values()) {
|
||||
if (t.name != null)
|
||||
key[tokenName[t.ordinal()].getIndex()] = t;
|
||||
}
|
||||
}
|
||||
|
||||
private void enterKeyword(String s, TokenKind token) {
|
||||
Name n = names.fromString(s);
|
||||
tokenName[token.ordinal()] = n;
|
||||
if (n.getIndex() > maxKey) maxKey = n.getIndex();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new token given a name; if the name corresponds to a token name,
|
||||
* a new token of the corresponding kind is returned; otherwise, an
|
||||
* identifier token is returned.
|
||||
*/
|
||||
TokenKind lookupKind(Name name) {
|
||||
return (name.getIndex() > maxKey) ? TokenKind.IDENTIFIER : key[name.getIndex()];
|
||||
}
|
||||
|
||||
TokenKind lookupKind(String name) {
|
||||
return lookupKind(names.fromString(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* This enum defines all tokens used by the javac scanner. A token is
|
||||
* optionally associated with a name.
|
||||
*/
|
||||
public enum TokenKind implements Formattable {
|
||||
EOF(),
|
||||
ERROR(),
|
||||
IDENTIFIER(Tag.NAMED),
|
||||
ABSTRACT("abstract"),
|
||||
ASSERT("assert", Tag.NAMED),
|
||||
BOOLEAN("boolean", Tag.NAMED),
|
||||
BREAK("break"),
|
||||
BYTE("byte", Tag.NAMED),
|
||||
CASE("case"),
|
||||
CATCH("catch"),
|
||||
CHAR("char", Tag.NAMED),
|
||||
CLASS("class"),
|
||||
CONST("const"),
|
||||
CONTINUE("continue"),
|
||||
DEFAULT("default"),
|
||||
DO("do"),
|
||||
DOUBLE("double", Tag.NAMED),
|
||||
ELSE("else"),
|
||||
ENUM("enum", Tag.NAMED),
|
||||
EXTENDS("extends"),
|
||||
FINAL("final"),
|
||||
FINALLY("finally"),
|
||||
FLOAT("float", Tag.NAMED),
|
||||
FOR("for"),
|
||||
GOTO("goto"),
|
||||
IF("if"),
|
||||
IMPLEMENTS("implements"),
|
||||
IMPORT("import"),
|
||||
INSTANCEOF("instanceof"),
|
||||
INT("int", Tag.NAMED),
|
||||
INTERFACE("interface"),
|
||||
LONG("long", Tag.NAMED),
|
||||
NATIVE("native"),
|
||||
NEW("new"),
|
||||
PACKAGE("package"),
|
||||
PRIVATE("private"),
|
||||
PROTECTED("protected"),
|
||||
PUBLIC("public"),
|
||||
RETURN("return"),
|
||||
SHORT("short", Tag.NAMED),
|
||||
STATIC("static"),
|
||||
STRICTFP("strictfp"),
|
||||
SUPER("super", Tag.NAMED),
|
||||
SWITCH("switch"),
|
||||
SYNCHRONIZED("synchronized"),
|
||||
THIS("this", Tag.NAMED),
|
||||
THROW("throw"),
|
||||
THROWS("throws"),
|
||||
TRANSIENT("transient"),
|
||||
TRY("try"),
|
||||
VOID("void", Tag.NAMED),
|
||||
VOLATILE("volatile"),
|
||||
WHILE("while"),
|
||||
INTLITERAL(Tag.NUMERIC),
|
||||
LONGLITERAL(Tag.NUMERIC),
|
||||
FLOATLITERAL(Tag.NUMERIC),
|
||||
DOUBLELITERAL(Tag.NUMERIC),
|
||||
CHARLITERAL(Tag.NUMERIC),
|
||||
STRINGLITERAL(Tag.STRING),
|
||||
TRUE("true", Tag.NAMED),
|
||||
FALSE("false", Tag.NAMED),
|
||||
NULL("null", Tag.NAMED),
|
||||
LPAREN("("),
|
||||
RPAREN(")"),
|
||||
LBRACE("{"),
|
||||
RBRACE("}"),
|
||||
LBRACKET("["),
|
||||
RBRACKET("]"),
|
||||
SEMI(";"),
|
||||
COMMA(","),
|
||||
DOT("."),
|
||||
ELLIPSIS("..."),
|
||||
EQ("="),
|
||||
GT(">"),
|
||||
LT("<"),
|
||||
BANG("!"),
|
||||
TILDE("~"),
|
||||
QUES("?"),
|
||||
COLON(":"),
|
||||
EQEQ("=="),
|
||||
LTEQ("<="),
|
||||
GTEQ(">="),
|
||||
BANGEQ("!="),
|
||||
AMPAMP("&&"),
|
||||
BARBAR("||"),
|
||||
PLUSPLUS("++"),
|
||||
SUBSUB("--"),
|
||||
PLUS("+"),
|
||||
SUB("-"),
|
||||
STAR("*"),
|
||||
SLASH("/"),
|
||||
AMP("&"),
|
||||
BAR("|"),
|
||||
CARET("^"),
|
||||
PERCENT("%"),
|
||||
LTLT("<<"),
|
||||
GTGT(">>"),
|
||||
GTGTGT(">>>"),
|
||||
PLUSEQ("+="),
|
||||
SUBEQ("-="),
|
||||
STAREQ("*="),
|
||||
SLASHEQ("/="),
|
||||
AMPEQ("&="),
|
||||
BAREQ("|="),
|
||||
CARETEQ("^="),
|
||||
PERCENTEQ("%="),
|
||||
LTLTEQ("<<="),
|
||||
GTGTEQ(">>="),
|
||||
GTGTGTEQ(">>>="),
|
||||
MONKEYS_AT("@"),
|
||||
CUSTOM;
|
||||
|
||||
public final String name;
|
||||
public final Tag tag;
|
||||
|
||||
TokenKind() {
|
||||
this(null, Tag.DEFAULT);
|
||||
}
|
||||
|
||||
TokenKind(String name) {
|
||||
this(name, Tag.DEFAULT);
|
||||
}
|
||||
|
||||
TokenKind(Tag tag) {
|
||||
this(null, tag);
|
||||
}
|
||||
|
||||
TokenKind(String name, Tag tag) {
|
||||
this.name = name;
|
||||
this.tag = tag;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
switch (this) {
|
||||
case IDENTIFIER:
|
||||
return "token.identifier";
|
||||
case CHARLITERAL:
|
||||
return "token.character";
|
||||
case STRINGLITERAL:
|
||||
return "token.string";
|
||||
case INTLITERAL:
|
||||
return "token.integer";
|
||||
case LONGLITERAL:
|
||||
return "token.long-integer";
|
||||
case FLOATLITERAL:
|
||||
return "token.float";
|
||||
case DOUBLELITERAL:
|
||||
return "token.double";
|
||||
case ERROR:
|
||||
return "token.bad-symbol";
|
||||
case EOF:
|
||||
return "token.end-of-input";
|
||||
case DOT: case COMMA: case SEMI: case LPAREN: case RPAREN:
|
||||
case LBRACKET: case RBRACKET: case LBRACE: case RBRACE:
|
||||
return "'" + name + "'";
|
||||
default:
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
public String getKind() {
|
||||
return "Token";
|
||||
}
|
||||
|
||||
public String toString(Locale locale, Messages messages) {
|
||||
return name != null ? toString() : messages.getLocalizedString(locale, "compiler.misc." + toString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the class representing a javac token. Each token has several fields
|
||||
* that are set by the javac lexer (i.e. start/end position, string value, etc).
|
||||
*/
|
||||
public static class Token {
|
||||
|
||||
/** tags constants **/
|
||||
enum Tag {
|
||||
DEFAULT,
|
||||
NAMED,
|
||||
STRING,
|
||||
NUMERIC;
|
||||
}
|
||||
|
||||
/** The token kind */
|
||||
public final TokenKind kind;
|
||||
|
||||
/** The start position of this token */
|
||||
public final int pos;
|
||||
|
||||
/** The end position of this token */
|
||||
public final int endPos;
|
||||
|
||||
/** Is this token preceeded by a deprecated comment? */
|
||||
public final boolean deprecatedFlag;
|
||||
|
||||
/** Is this token preceeded by a deprecated comment? */
|
||||
public String docComment;
|
||||
|
||||
Token(TokenKind kind, int pos, int endPos,
|
||||
boolean deprecatedFlag) {
|
||||
this.kind = kind;
|
||||
this.pos = pos;
|
||||
this.endPos = endPos;
|
||||
this.deprecatedFlag = deprecatedFlag;
|
||||
checkKind();
|
||||
}
|
||||
|
||||
Token[] split(Tokens tokens) {
|
||||
if (kind.name.length() < 2 || kind.tag != Tag.DEFAULT) {
|
||||
throw new AssertionError("Cant split" + kind);
|
||||
}
|
||||
|
||||
TokenKind t1 = tokens.lookupKind(kind.name.substring(0, 1));
|
||||
TokenKind t2 = tokens.lookupKind(kind.name.substring(1));
|
||||
|
||||
if (t1 == null || t2 == null) {
|
||||
throw new AssertionError("Cant split - bad subtokens");
|
||||
}
|
||||
return new Token[] {
|
||||
new Token(t1, pos, pos + t1.name.length(), deprecatedFlag),
|
||||
new Token(t2, pos + t1.name.length(), endPos, false)
|
||||
};
|
||||
}
|
||||
|
||||
protected void checkKind() {
|
||||
if (kind.tag != Tag.DEFAULT) {
|
||||
throw new AssertionError("Bad token kind - expected " + Tag.STRING);
|
||||
}
|
||||
}
|
||||
|
||||
public Name name() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public String stringVal() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public int radix() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
final static class NamedToken extends Token {
|
||||
/** The name of this token */
|
||||
public final Name name;
|
||||
|
||||
public NamedToken(TokenKind kind, int pos, int endPos, Name name, boolean deprecatedFlag) {
|
||||
super(kind, pos, endPos, deprecatedFlag);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
protected void checkKind() {
|
||||
if (kind.tag != Tag.NAMED) {
|
||||
throw new AssertionError("Bad token kind - expected " + Tag.NAMED);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Name name() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
static class StringToken extends Token {
|
||||
/** The string value of this token */
|
||||
public final String stringVal;
|
||||
|
||||
public StringToken(TokenKind kind, int pos, int endPos, String stringVal, boolean deprecatedFlag) {
|
||||
super(kind, pos, endPos, deprecatedFlag);
|
||||
this.stringVal = stringVal;
|
||||
}
|
||||
|
||||
protected void checkKind() {
|
||||
if (kind.tag != Tag.STRING) {
|
||||
throw new AssertionError("Bad token kind - expected " + Tag.STRING);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String stringVal() {
|
||||
return stringVal;
|
||||
}
|
||||
}
|
||||
|
||||
final static class NumericToken extends StringToken {
|
||||
/** The 'radix' value of this token */
|
||||
public final int radix;
|
||||
|
||||
public NumericToken(TokenKind kind, int pos, int endPos, String stringVal, int radix, boolean deprecatedFlag) {
|
||||
super(kind, pos, endPos, stringVal, deprecatedFlag);
|
||||
this.radix = radix;
|
||||
}
|
||||
|
||||
protected void checkKind() {
|
||||
if (kind.tag != Tag.NUMERIC) {
|
||||
throw new AssertionError("Bad token kind - expected " + Tag.NUMERIC);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int radix() {
|
||||
return radix;
|
||||
}
|
||||
}
|
||||
|
||||
public static final Token DUMMY =
|
||||
new Token(TokenKind.ERROR, 0, 0, false);
|
||||
}
|
@ -0,0 +1,227 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package com.sun.tools.javac.parser;
|
||||
|
||||
import com.sun.tools.javac.file.JavacFileManager;
|
||||
import java.nio.CharBuffer;
|
||||
import com.sun.tools.javac.util.Log;
|
||||
import static com.sun.tools.javac.util.LayoutCharacters.*;
|
||||
|
||||
/** The char reader used by the javac lexer/tokenizer. Returns the sequence of
|
||||
* characters contained in the input stream, handling unicode escape accordingly.
|
||||
* Additionally, it provide features for saving chars into a buffer and to retrieve
|
||||
* them at a later stage.
|
||||
*
|
||||
* <p><b>This is NOT part of any supported API.
|
||||
* If you write code that depends on this, you do so at your own risk.
|
||||
* This code and its internal interfaces are subject to change or
|
||||
* deletion without notice.</b>
|
||||
*/
|
||||
public class UnicodeReader {
|
||||
|
||||
/** The input buffer, index of next character to be read,
|
||||
* index of one past last character in buffer.
|
||||
*/
|
||||
protected char[] buf;
|
||||
protected int bp;
|
||||
protected final int buflen;
|
||||
|
||||
/** The current character.
|
||||
*/
|
||||
protected char ch;
|
||||
|
||||
/** The buffer index of the last converted unicode character
|
||||
*/
|
||||
protected int unicodeConversionBp = -1;
|
||||
|
||||
protected Log log;
|
||||
|
||||
/**
|
||||
* Create a scanner from the input array. This method might
|
||||
* modify the array. To avoid copying the input array, ensure
|
||||
* that {@code inputLength < input.length} or
|
||||
* {@code input[input.length -1]} is a white space character.
|
||||
*
|
||||
* @param fac the factory which created this Scanner
|
||||
* @param input the input, might be modified
|
||||
* @param inputLength the size of the input.
|
||||
* Must be positive and less than or equal to input.length.
|
||||
*/
|
||||
protected UnicodeReader(ScannerFactory sf, CharBuffer buffer) {
|
||||
this(sf, JavacFileManager.toArray(buffer), buffer.limit());
|
||||
}
|
||||
|
||||
protected UnicodeReader(ScannerFactory sf, char[] input, int inputLength) {
|
||||
log = sf.log;
|
||||
if (inputLength == input.length) {
|
||||
if (input.length > 0 && Character.isWhitespace(input[input.length - 1])) {
|
||||
inputLength--;
|
||||
} else {
|
||||
char[] newInput = new char[inputLength + 1];
|
||||
System.arraycopy(input, 0, newInput, 0, input.length);
|
||||
input = newInput;
|
||||
}
|
||||
}
|
||||
buf = input;
|
||||
buflen = inputLength;
|
||||
buf[buflen] = EOI;
|
||||
bp = -1;
|
||||
scanChar();
|
||||
}
|
||||
|
||||
/** Read next character.
|
||||
*/
|
||||
protected void scanChar() {
|
||||
if (bp < buflen) {
|
||||
ch = buf[++bp];
|
||||
if (ch == '\\') {
|
||||
convertUnicode();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Convert unicode escape; bp points to initial '\' character
|
||||
* (Spec 3.3).
|
||||
*/
|
||||
protected void convertUnicode() {
|
||||
if (ch == '\\' && unicodeConversionBp != bp) {
|
||||
bp++; ch = buf[bp];
|
||||
if (ch == 'u') {
|
||||
do {
|
||||
bp++; ch = buf[bp];
|
||||
} while (ch == 'u');
|
||||
int limit = bp + 3;
|
||||
if (limit < buflen) {
|
||||
int d = digit(bp, 16);
|
||||
int code = d;
|
||||
while (bp < limit && d >= 0) {
|
||||
bp++; ch = buf[bp];
|
||||
d = digit(bp, 16);
|
||||
code = (code << 4) + d;
|
||||
}
|
||||
if (d >= 0) {
|
||||
ch = (char)code;
|
||||
unicodeConversionBp = bp;
|
||||
return;
|
||||
}
|
||||
}
|
||||
log.error(bp, "illegal.unicode.esc");
|
||||
} else {
|
||||
bp--;
|
||||
ch = '\\';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Are surrogates supported?
|
||||
*/
|
||||
final static boolean surrogatesSupported = surrogatesSupported();
|
||||
private static boolean surrogatesSupported() {
|
||||
try {
|
||||
Character.isHighSurrogate('a');
|
||||
return true;
|
||||
} catch (NoSuchMethodError ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Scan surrogate pairs. If 'ch' is a high surrogate and
|
||||
* the next character is a low surrogate, then put the low
|
||||
* surrogate in 'ch', and return the high surrogate.
|
||||
* otherwise, just return 0.
|
||||
*/
|
||||
protected char scanSurrogates() {
|
||||
if (surrogatesSupported && Character.isHighSurrogate(ch)) {
|
||||
char high = ch;
|
||||
|
||||
scanChar();
|
||||
|
||||
if (Character.isLowSurrogate(ch)) {
|
||||
return high;
|
||||
}
|
||||
|
||||
ch = high;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Convert an ASCII digit from its base (8, 10, or 16)
|
||||
* to its value.
|
||||
*/
|
||||
protected int digit(int pos, int base) {
|
||||
char c = ch;
|
||||
int result = Character.digit(c, base);
|
||||
if (result >= 0 && c > 0x7f) {
|
||||
log.error(pos + 1, "illegal.nonascii.digit");
|
||||
ch = "0123456789abcdef".charAt(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
protected boolean isUnicode() {
|
||||
return unicodeConversionBp == bp;
|
||||
}
|
||||
|
||||
protected void skipChar() {
|
||||
bp++;
|
||||
}
|
||||
|
||||
protected char peekChar() {
|
||||
return buf[bp + 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of the input buffer, up to its inputLength.
|
||||
* Unicode escape sequences are not translated.
|
||||
*/
|
||||
public char[] getRawCharacters() {
|
||||
char[] chars = new char[buflen];
|
||||
System.arraycopy(buf, 0, chars, 0, buflen);
|
||||
return chars;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of a character array subset of the input buffer.
|
||||
* The returned array begins at the <code>beginIndex</code> and
|
||||
* extends to the character at index <code>endIndex - 1</code>.
|
||||
* Thus the length of the substring is <code>endIndex-beginIndex</code>.
|
||||
* This behavior is like
|
||||
* <code>String.substring(beginIndex, endIndex)</code>.
|
||||
* Unicode escape sequences are not translated.
|
||||
*
|
||||
* @param beginIndex the beginning index, inclusive.
|
||||
* @param endIndex the ending index, exclusive.
|
||||
* @throws IndexOutOfBounds if either offset is outside of the
|
||||
* array bounds
|
||||
*/
|
||||
public char[] getRawCharacters(int beginIndex, int endIndex) {
|
||||
int length = endIndex - beginIndex;
|
||||
char[] chars = new char[length];
|
||||
System.arraycopy(buf, beginIndex, chars, 0, length);
|
||||
return chars;
|
||||
}
|
||||
}
|
@ -1072,9 +1072,9 @@ public class JavacProcessingEnvironment implements ProcessingEnvironment, Closea
|
||||
Assert.checkNonNull(names);
|
||||
next.put(Names.namesKey, names);
|
||||
|
||||
Keywords keywords = Keywords.instance(context);
|
||||
Assert.checkNonNull(keywords);
|
||||
next.put(Keywords.keywordsKey, keywords);
|
||||
Tokens tokens = Tokens.instance(context);
|
||||
Assert.checkNonNull(tokens);
|
||||
next.put(Tokens.tokensKey, tokens);
|
||||
|
||||
JavaCompiler oldCompiler = JavaCompiler.instance(context);
|
||||
JavaCompiler nextCompiler = JavaCompiler.instance(next);
|
||||
|
@ -1943,6 +1943,55 @@ compiler.err.string.switch.not.supported.in.source=\
|
||||
strings in switch are not supported in -source {0}\n\
|
||||
(use -source 7 or higher to enable strings in switch)
|
||||
|
||||
########################################
|
||||
# Diagnostics for verbose resolution
|
||||
# used by Resolve (debug only)
|
||||
########################################
|
||||
|
||||
# 0: number, 1: symbol, 2: unused
|
||||
compiler.misc.applicable.method.found=\
|
||||
#{0} applicable method found: {1}
|
||||
|
||||
# 0: number, 1: symbol, 2: message segment
|
||||
compiler.misc.applicable.method.found.1=\
|
||||
#{0} applicable method found: {1}\n\
|
||||
({2})
|
||||
|
||||
# 0: number, 1: symbol, 2: message segment
|
||||
compiler.misc.not.applicable.method.found=\
|
||||
#{0} not applicable method found: {1}\n\
|
||||
({2})
|
||||
|
||||
# 0: type
|
||||
compiler.misc.full.inst.sig=\
|
||||
fully instantiated to: {0}
|
||||
|
||||
# 0: type
|
||||
compiler.misc.partial.inst.sig=\
|
||||
partially instantiated to: {0}
|
||||
|
||||
# 0: name, 1: symbol, 2: number, 3: MethodResolutionPhase, 4: list of type or message segment, 5: list of type or message segment
|
||||
compiler.note.verbose.resolve.multi=\
|
||||
resolving method {0} in type {1} to candidate {2}\n\
|
||||
phase: {3}\n\
|
||||
with actuals: {4}\n\
|
||||
with type-args: {5}\n\
|
||||
candidates:
|
||||
|
||||
# 0: name, 1: symbol, 2: unused, 3: MethodResolutionPhase, 4: list of type or message segment, 5: list of type or message segment
|
||||
compiler.note.verbose.resolve.multi.1=\
|
||||
erroneous resolution for method {0} in type {1}\n\
|
||||
phase: {3}\n\
|
||||
with actuals: {4}\n\
|
||||
with type-args: {5}\n\
|
||||
candidates:
|
||||
|
||||
# 0: symbol, 1: type, 2: type
|
||||
compiler.note.deferred.method.inst=\
|
||||
Deferred instantiation of method {0}\n\
|
||||
instantiated signature: {1}\n\
|
||||
target-type: {2}
|
||||
|
||||
########################################
|
||||
# Diagnostics for where clause implementation
|
||||
# used by the RichDiagnosticFormatter.
|
||||
|
@ -25,11 +25,6 @@
|
||||
|
||||
package com.sun.tools.javac.util;
|
||||
|
||||
import com.sun.tools.javac.code.Source;
|
||||
import com.sun.tools.javac.main.JavacOption;
|
||||
import com.sun.tools.javac.main.OptionName;
|
||||
import com.sun.tools.javac.main.RecognizedOptions;
|
||||
import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
@ -54,6 +49,15 @@ import java.util.Map;
|
||||
import javax.tools.JavaFileObject;
|
||||
import javax.tools.JavaFileObject.Kind;
|
||||
|
||||
import com.sun.tools.javac.code.Lint;
|
||||
import com.sun.tools.javac.code.Source;
|
||||
import com.sun.tools.javac.file.FSInfo;
|
||||
import com.sun.tools.javac.file.Locations;
|
||||
import com.sun.tools.javac.main.JavacOption;
|
||||
import com.sun.tools.javac.main.OptionName;
|
||||
import com.sun.tools.javac.main.RecognizedOptions;
|
||||
import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
|
||||
|
||||
/**
|
||||
* Utility methods for building a filemanager.
|
||||
* There are no references here to file-system specific objects such as
|
||||
@ -63,15 +67,21 @@ public abstract class BaseFileManager {
|
||||
protected BaseFileManager(Charset charset) {
|
||||
this.charset = charset;
|
||||
byteBufferCache = new ByteBufferCache();
|
||||
locations = createLocations();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the context for JavacPathFileManager.
|
||||
*/
|
||||
protected void setContext(Context context) {
|
||||
public void setContext(Context context) {
|
||||
log = Log.instance(context);
|
||||
options = Options.instance(context);
|
||||
classLoaderClass = options.get("procloader");
|
||||
locations.update(log, options, Lint.instance(context), FSInfo.instance(context));
|
||||
}
|
||||
|
||||
protected Locations createLocations() {
|
||||
return new Locations();
|
||||
}
|
||||
|
||||
/**
|
||||
@ -88,6 +98,8 @@ public abstract class BaseFileManager {
|
||||
|
||||
protected String classLoaderClass;
|
||||
|
||||
protected Locations locations;
|
||||
|
||||
protected Source getSource() {
|
||||
String sourceName = options.get(OptionName.SOURCE);
|
||||
Source source = null;
|
||||
|
@ -80,7 +80,7 @@ public class DocletInvoker {
|
||||
cpString = appendPath(System.getProperty("env.class.path"), cpString);
|
||||
cpString = appendPath(System.getProperty("java.class.path"), cpString);
|
||||
cpString = appendPath(docletPath, cpString);
|
||||
URL[] urls = com.sun.tools.javac.file.Paths.pathToURLs(cpString);
|
||||
URL[] urls = com.sun.tools.javac.file.Locations.pathToURLs(cpString);
|
||||
if (docletParentClassLoader == null)
|
||||
appClassLoader = new URLClassLoader(urls, getDelegationClassLoader(docletClassName));
|
||||
else
|
||||
|
@ -39,7 +39,6 @@ import javax.tools.StandardLocation;
|
||||
|
||||
import com.sun.tools.javac.code.Symbol.CompletionFailure;
|
||||
import com.sun.tools.javac.comp.Annotate;
|
||||
import com.sun.tools.javac.parser.DocCommentScanner;
|
||||
import com.sun.tools.javac.tree.JCTree;
|
||||
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
|
||||
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
|
||||
|
11
langtools/test/tools/javac/7102515/T7102515.java
Normal file
11
langtools/test/tools/javac/7102515/T7102515.java
Normal file
@ -0,0 +1,11 @@
|
||||
/*
|
||||
* @test /nodynamiccopyright/
|
||||
* @bug 7102515
|
||||
* @summary javac running very very long and not returning
|
||||
* @compile/fail/ref=T7102515.out -XDrawDiagnostics T7102515.java
|
||||
*/
|
||||
|
||||
class T7102515 {
|
||||
T7102515 badBinary = new T7102515() + new T7102515();
|
||||
Object badUnary = badBinary++;
|
||||
}
|
3
langtools/test/tools/javac/7102515/T7102515.out
Normal file
3
langtools/test/tools/javac/7102515/T7102515.out
Normal file
@ -0,0 +1,3 @@
|
||||
T7102515.java:9:41: compiler.err.operator.cant.be.applied.1: +, T7102515, T7102515
|
||||
T7102515.java:10:32: compiler.err.operator.cant.be.applied: ++, T7102515, null
|
||||
2 errors
|
262
langtools/test/tools/javac/T7093325.java
Normal file
262
langtools/test/tools/javac/T7093325.java
Normal file
@ -0,0 +1,262 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 7093325
|
||||
* @summary Redundant entry in bytecode exception table
|
||||
*/
|
||||
|
||||
import com.sun.source.util.JavacTask;
|
||||
import com.sun.tools.classfile.Attribute;
|
||||
import com.sun.tools.classfile.ClassFile;
|
||||
import com.sun.tools.classfile.Code_attribute;
|
||||
import com.sun.tools.classfile.ConstantPool.*;
|
||||
import com.sun.tools.classfile.Method;
|
||||
import com.sun.tools.javac.api.JavacTool;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import javax.tools.JavaCompiler;
|
||||
import javax.tools.JavaFileObject;
|
||||
import javax.tools.SimpleJavaFileObject;
|
||||
import javax.tools.StandardJavaFileManager;
|
||||
import javax.tools.ToolProvider;
|
||||
|
||||
|
||||
public class T7093325 {
|
||||
|
||||
/** global decls ***/
|
||||
|
||||
// Create a single file manager and reuse it for each compile to save time.
|
||||
static StandardJavaFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
|
||||
|
||||
//statistics
|
||||
static int checkCount = 0;
|
||||
|
||||
enum StatementKind {
|
||||
THROW("throw new RuntimeException();", false, false),
|
||||
RETURN_NONEMPTY("System.out.println(); return;", true, false),
|
||||
RETURN_EMPTY("return;", true, true),
|
||||
APPLY("System.out.println();", true, false);
|
||||
|
||||
String stmt;
|
||||
boolean canInline;
|
||||
boolean empty;
|
||||
|
||||
private StatementKind(String stmt, boolean canInline, boolean empty) {
|
||||
this.stmt = stmt;
|
||||
this.canInline = canInline;
|
||||
this.empty = empty;
|
||||
}
|
||||
}
|
||||
|
||||
enum CatchArity {
|
||||
NONE(""),
|
||||
ONE("catch (A a) { #S1 }"),
|
||||
TWO("catch (B b) { #S2 }"),
|
||||
THREE("catch (C c) { #S3 }"),
|
||||
FOUR("catch (D d) { #S4 }");
|
||||
|
||||
String catchStr;
|
||||
|
||||
private CatchArity(String catchStr) {
|
||||
this.catchStr = catchStr;
|
||||
}
|
||||
|
||||
String catchers() {
|
||||
if (this.ordinal() == 0) {
|
||||
return catchStr;
|
||||
} else {
|
||||
return CatchArity.values()[this.ordinal() - 1].catchers() + catchStr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
for (CatchArity ca : CatchArity.values()) {
|
||||
for (StatementKind stmt0 : StatementKind.values()) {
|
||||
if (ca.ordinal() == 0) {
|
||||
new T7093325(ca, stmt0).compileAndCheck();
|
||||
continue;
|
||||
}
|
||||
for (StatementKind stmt1 : StatementKind.values()) {
|
||||
if (ca.ordinal() == 1) {
|
||||
new T7093325(ca, stmt0, stmt1).compileAndCheck();
|
||||
continue;
|
||||
}
|
||||
for (StatementKind stmt2 : StatementKind.values()) {
|
||||
if (ca.ordinal() == 2) {
|
||||
new T7093325(ca, stmt0, stmt1, stmt2).compileAndCheck();
|
||||
continue;
|
||||
}
|
||||
for (StatementKind stmt3 : StatementKind.values()) {
|
||||
if (ca.ordinal() == 3) {
|
||||
new T7093325(ca, stmt0, stmt1, stmt2, stmt3).compileAndCheck();
|
||||
continue;
|
||||
}
|
||||
for (StatementKind stmt4 : StatementKind.values()) {
|
||||
if (ca.ordinal() == 4) {
|
||||
new T7093325(ca, stmt0, stmt1, stmt2, stmt3, stmt4).compileAndCheck();
|
||||
continue;
|
||||
}
|
||||
for (StatementKind stmt5 : StatementKind.values()) {
|
||||
new T7093325(ca, stmt0, stmt1, stmt2, stmt3, stmt4, stmt5).compileAndCheck();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("Total checks made: " + checkCount);
|
||||
}
|
||||
|
||||
/** instance decls **/
|
||||
|
||||
CatchArity ca;
|
||||
StatementKind[] stmts;
|
||||
|
||||
public T7093325(CatchArity ca, StatementKind... stmts) {
|
||||
this.ca = ca;
|
||||
this.stmts = stmts;
|
||||
}
|
||||
|
||||
void compileAndCheck() throws Exception {
|
||||
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
|
||||
JavaSource source = new JavaSource();
|
||||
JavacTask ct = (JavacTask)tool.getTask(null, fm, null,
|
||||
null, null, Arrays.asList(source));
|
||||
ct.call();
|
||||
verifyBytecode(source);
|
||||
}
|
||||
|
||||
void verifyBytecode(JavaSource source) {
|
||||
checkCount++;
|
||||
boolean lastInlined = false;
|
||||
boolean hasCode = false;
|
||||
int gapsCount = 0;
|
||||
for (int i = 0; i < stmts.length ; i++) {
|
||||
lastInlined = stmts[i].canInline;
|
||||
hasCode = hasCode || !stmts[i].empty;
|
||||
if (lastInlined && hasCode) {
|
||||
hasCode = false;
|
||||
gapsCount++;
|
||||
}
|
||||
}
|
||||
if (!lastInlined) {
|
||||
gapsCount++;
|
||||
}
|
||||
|
||||
//System.out.printf("gaps %d \n %s \n", gapsCount, source.toString());
|
||||
|
||||
File compiledTest = new File("Test.class");
|
||||
try {
|
||||
ClassFile cf = ClassFile.read(compiledTest);
|
||||
if (cf == null) {
|
||||
throw new Error("Classfile not found: " + compiledTest.getName());
|
||||
}
|
||||
|
||||
Method test_method = null;
|
||||
for (Method m : cf.methods) {
|
||||
if (m.getName(cf.constant_pool).equals("test")) {
|
||||
test_method = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (test_method == null) {
|
||||
throw new Error("Method test() not found in class Test");
|
||||
}
|
||||
|
||||
Code_attribute code = null;
|
||||
for (Attribute a : test_method.attributes) {
|
||||
if (a.getName(cf.constant_pool).equals(Attribute.Code)) {
|
||||
code = (Code_attribute)a;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (code == null) {
|
||||
throw new Error("Code attribute not found in method test()");
|
||||
}
|
||||
|
||||
int actualGapsCount = 0;
|
||||
for (int i = 0; i < code.exception_table_langth ; i++) {
|
||||
int catchType = code.exception_table[i].catch_type;
|
||||
if (catchType == 0) { //any
|
||||
actualGapsCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if (actualGapsCount != gapsCount) {
|
||||
throw new Error("Bad exception table for test()\n" +
|
||||
"expected gaps: " + gapsCount + "\n" +
|
||||
"found gaps: " + actualGapsCount + "\n" +
|
||||
source);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new Error("error reading " + compiledTest +": " + e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class JavaSource extends SimpleJavaFileObject {
|
||||
|
||||
static final String source_template =
|
||||
"class A extends RuntimeException {} \n" +
|
||||
"class B extends RuntimeException {} \n" +
|
||||
"class C extends RuntimeException {} \n" +
|
||||
"class D extends RuntimeException {} \n" +
|
||||
"class E extends RuntimeException {} \n" +
|
||||
"class Test {\n" +
|
||||
" void test() {\n" +
|
||||
" try { #S0 } #C finally { System.out.println(); }\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
|
||||
String source;
|
||||
|
||||
public JavaSource() {
|
||||
super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
|
||||
source = source_template.replace("#C", ca.catchers());
|
||||
source = source.replace("#S0", stmts[0].stmt);
|
||||
for (int i = 1; i < ca.ordinal() + 1; i++) {
|
||||
source = source.replace("#S" + i, stmts[i].stmt);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return source;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
|
||||
return source;
|
||||
}
|
||||
}
|
||||
}
|
@ -32,6 +32,7 @@
|
||||
|
||||
import com.sun.tools.javac.api.JavacTaskImpl;
|
||||
import com.sun.tools.javac.parser.*;
|
||||
import com.sun.tools.javac.parser.Tokens.Token;
|
||||
import com.sun.tools.javac.util.*;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
@ -93,7 +94,7 @@ public class TestJavacTaskScanner extends ToolTester {
|
||||
|
||||
check(numTokens, "#Tokens", 1222);
|
||||
check(numParseTypeElements, "#parseTypeElements", 136);
|
||||
check(numAllMembers, "#allMembers", 67);
|
||||
check(numAllMembers, "#allMembers", 52);
|
||||
}
|
||||
|
||||
void check(int value, String name, int expected) {
|
||||
@ -206,7 +207,8 @@ class MyScanner extends Scanner {
|
||||
|
||||
public void nextToken() {
|
||||
super.nextToken();
|
||||
System.err.format("Saw token %s (%s)%n", token(), name());
|
||||
Token tk = token();
|
||||
System.err.format("Saw token %s %n", tk.kind);
|
||||
test.numTokens++;
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @test
|
||||
* @bug 7096014
|
||||
* @summary Javac tokens should retain state
|
||||
* @compile -Xlint -Werror DeprecatedDocComment3.java
|
||||
*/
|
||||
|
||||
class DeprecatedDocComment3 {
|
||||
static class Foo { }
|
||||
|
||||
; /** @deprecated */ ;
|
||||
|
||||
static class A {}
|
||||
|
||||
static class B {
|
||||
A a; //not deprecated!
|
||||
}
|
||||
}
|
@ -35,7 +35,7 @@ import com.sun.tools.javac.code.*;
|
||||
import com.sun.tools.javac.file.*;
|
||||
import com.sun.tools.javac.main.Main;
|
||||
import com.sun.tools.javac.main.JavaCompiler;
|
||||
import com.sun.tools.javac.parser.Token;
|
||||
import com.sun.tools.javac.parser.Tokens.TokenKind;
|
||||
import com.sun.tools.javac.util.*;
|
||||
import com.sun.tools.javac.util.AbstractDiagnosticFormatter.SimpleConfiguration;
|
||||
import javax.lang.model.SourceVersion;
|
||||
@ -319,7 +319,7 @@ class ArgTypeCompilerFactory implements Example.Compiler.Factory {
|
||||
return "modifier";
|
||||
if (o instanceof KindName)
|
||||
return "symbol kind";
|
||||
if (o instanceof Token)
|
||||
if (o instanceof TokenKind)
|
||||
return "token";
|
||||
if (o instanceof Symbol)
|
||||
return "symbol";
|
||||
|
@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
// key: compiler.misc.applicable.method.found
|
||||
// key: compiler.note.verbose.resolve.multi
|
||||
// options: -XDverboseResolution=applicable,success
|
||||
|
||||
class ApplicableMethodFound {
|
||||
|
||||
void m() {}
|
||||
|
||||
{ m(); }
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
// key: compiler.misc.applicable.method.found.1
|
||||
// key: compiler.note.verbose.resolve.multi
|
||||
// key: compiler.misc.full.inst.sig
|
||||
// options: -XDverboseResolution=applicable,success
|
||||
|
||||
class ApplicableMethodFound1 {
|
||||
|
||||
<X> void m(X x) {}
|
||||
|
||||
{ m(1); }
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
// key: compiler.misc.applicable.method.found.1
|
||||
// key: compiler.note.verbose.resolve.multi
|
||||
// key: compiler.note.deferred.method.inst
|
||||
// key: compiler.misc.partial.inst.sig
|
||||
// options: -XDverboseResolution=applicable,success,deferred-inference
|
||||
|
||||
class DeferredMethodInst {
|
||||
|
||||
<X> X m() { return null; }
|
||||
|
||||
{ Integer i = m(); }
|
||||
}
|
34
langtools/test/tools/javac/diags/examples/FullInstSig.java
Normal file
34
langtools/test/tools/javac/diags/examples/FullInstSig.java
Normal file
@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
// key: compiler.misc.applicable.method.found.1
|
||||
// key: compiler.note.verbose.resolve.multi
|
||||
// key: compiler.misc.full.inst.sig
|
||||
// options: -XDverboseResolution=applicable,success
|
||||
|
||||
class FullInstSig {
|
||||
|
||||
<X> void m(X x) {}
|
||||
|
||||
{ m(1); }
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
// key: compiler.misc.not.applicable.method.found
|
||||
// key: compiler.note.verbose.resolve.multi.1
|
||||
// key: compiler.err.cant.apply.symbol.1
|
||||
// key: compiler.misc.no.conforming.assignment.exists
|
||||
// options: -XDverboseResolution=inapplicable,failure
|
||||
|
||||
class NotApplicableMethodFound {
|
||||
|
||||
void m(int i) {}
|
||||
|
||||
{ m(""); }
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
// key: compiler.misc.applicable.method.found.1
|
||||
// key: compiler.note.verbose.resolve.multi
|
||||
// key: compiler.misc.partial.inst.sig
|
||||
// options: -XDverboseResolution=applicable,success
|
||||
|
||||
class PartialInstSig {
|
||||
|
||||
<X> X m() { return null; }
|
||||
|
||||
{ m(); }
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
// key: compiler.misc.applicable.method.found
|
||||
// key: compiler.note.verbose.resolve.multi
|
||||
// options: -XDverboseResolution=applicable,success
|
||||
|
||||
class VerboseResolveMulti {
|
||||
|
||||
void m() {}
|
||||
|
||||
{ m(); }
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
// key: compiler.misc.not.applicable.method.found
|
||||
// key: compiler.note.verbose.resolve.multi.1
|
||||
// key: compiler.err.cant.apply.symbol.1
|
||||
// key: compiler.misc.no.conforming.assignment.exists
|
||||
// options: -XDverboseResolution=inapplicable,failure
|
||||
|
||||
class VerboseResolveMulti1 {
|
||||
|
||||
void m(int i) {}
|
||||
|
||||
{ m(""); }
|
||||
}
|
@ -47,7 +47,7 @@ case "$OS" in
|
||||
;;
|
||||
CYGWIN* )
|
||||
FS="/"
|
||||
SCR=`pwd | cygpath -d`
|
||||
SCR=`pwd | cygpath -d -f -`
|
||||
;;
|
||||
Windows* )
|
||||
FS="\\"
|
||||
|
68
langtools/test/tools/javac/resolve/Candidate.java
Normal file
68
langtools/test/tools/javac/resolve/Candidate.java
Normal file
@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
|
||||
@interface Candidate {
|
||||
/**
|
||||
* the candidate position (line/col of the method call for which this candidate
|
||||
* is a potential overload candidate)
|
||||
*/
|
||||
Pos pos() default @Pos(userDefined=false);
|
||||
/**
|
||||
* resolution phases for which this candidate is applicable
|
||||
*/
|
||||
Phase[] applicable() default { };
|
||||
/**
|
||||
* is this candidate the most specific (in the resolution phases for which it
|
||||
* is also applicable)
|
||||
*/
|
||||
boolean mostSpecific() default false;
|
||||
/**
|
||||
* this candidate inferred signature (in the resolution phases for which it
|
||||
* is also applicable, in case it corresponds to a generic method)
|
||||
*/
|
||||
String sig() default "";
|
||||
}
|
||||
|
||||
enum Phase {
|
||||
BASIC("BASIC"),
|
||||
BOX("BOX"),
|
||||
VARARGS("VARARITY");
|
||||
|
||||
final String javacString;
|
||||
|
||||
private Phase(String javacString) {
|
||||
this.javacString = javacString;
|
||||
}
|
||||
|
||||
static Phase fromString(String s) {
|
||||
for (Phase phase : Phase.values()) {
|
||||
if (phase.javacString.equals(s)) {
|
||||
return phase;
|
||||
}
|
||||
}
|
||||
throw new AssertionError("Invalid resolution phase string " + s);
|
||||
}
|
||||
}
|
31
langtools/test/tools/javac/resolve/Pos.java
Normal file
31
langtools/test/tools/javac/resolve/Pos.java
Normal file
@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.ANNOTATION_TYPE)
|
||||
@interface Pos {
|
||||
long line() default -1;
|
||||
long col() default -1;
|
||||
boolean userDefined() default true;
|
||||
}
|
475
langtools/test/tools/javac/resolve/ResolveHarness.java
Normal file
475
langtools/test/tools/javac/resolve/ResolveHarness.java
Normal file
@ -0,0 +1,475 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 7098660
|
||||
* @summary Write better overload resolution/inference tests
|
||||
* @library ../lib
|
||||
* @build JavacTestingAbstractProcessor ResolveHarness
|
||||
* @run main ResolveHarness
|
||||
*/
|
||||
|
||||
import com.sun.source.util.JavacTask;
|
||||
import com.sun.tools.javac.api.ClientCodeWrapper.DiagnosticSourceUnwrapper;
|
||||
import com.sun.tools.javac.code.Type.MethodType;
|
||||
import com.sun.tools.javac.util.JCDiagnostic;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Set;
|
||||
import java.util.Arrays;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.processing.AbstractProcessor;
|
||||
import javax.annotation.processing.RoundEnvironment;
|
||||
import javax.annotation.processing.SupportedAnnotationTypes;
|
||||
import javax.lang.model.element.Element;
|
||||
import javax.lang.model.element.TypeElement;
|
||||
import javax.tools.Diagnostic;
|
||||
import javax.tools.Diagnostic.Kind;
|
||||
import javax.tools.DiagnosticListener;
|
||||
import javax.tools.JavaCompiler;
|
||||
import javax.tools.JavaFileObject;
|
||||
import javax.tools.StandardJavaFileManager;
|
||||
import javax.tools.ToolProvider;
|
||||
|
||||
import static javax.tools.StandardLocation.*;
|
||||
|
||||
public class ResolveHarness implements javax.tools.DiagnosticListener<JavaFileObject> {
|
||||
|
||||
static int nerrors = 0;
|
||||
|
||||
static final JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
|
||||
static final StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
fm.setLocation(SOURCE_PATH,
|
||||
Arrays.asList(new File(System.getProperty("test.src"), "tests")));
|
||||
for (JavaFileObject jfo : fm.list(SOURCE_PATH, "", Collections.singleton(JavaFileObject.Kind.SOURCE), true)) {
|
||||
new ResolveHarness(jfo).check();
|
||||
}
|
||||
if (nerrors > 0) {
|
||||
throw new AssertionError("Errors were found");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
JavaFileObject jfo;
|
||||
DiagnosticProcessor[] diagProcessors;
|
||||
Map<ElementKey, Candidate> candidatesMap = new HashMap<ElementKey, Candidate>();
|
||||
Set<String> declaredKeys = new HashSet<>();
|
||||
List<Diagnostic<? extends JavaFileObject>> diags = new ArrayList<>();
|
||||
List<ElementKey> seenCandidates = new ArrayList<>();
|
||||
|
||||
protected ResolveHarness(JavaFileObject jfo) {
|
||||
this.jfo = jfo;
|
||||
this.diagProcessors = new DiagnosticProcessor[] {
|
||||
new VerboseResolutionNoteProcessor(),
|
||||
new VerboseDeferredInferenceNoteProcessor(),
|
||||
new ErrorProcessor()
|
||||
};
|
||||
}
|
||||
|
||||
protected void check() throws Exception {
|
||||
String[] options = {
|
||||
"-XDshouldStopPolicy=ATTR",
|
||||
"-XDverboseResolution=success,failure,applicable,inapplicable,deferred-inference"
|
||||
};
|
||||
|
||||
AbstractProcessor[] processors = { new ResolveCandidateFinder(), null };
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
DiagnosticListener<? super JavaFileObject>[] diagListeners =
|
||||
new DiagnosticListener[] { new DiagnosticHandler(false), new DiagnosticHandler(true) };
|
||||
|
||||
for (int i = 0 ; i < options.length ; i ++) {
|
||||
JavacTask ct = (JavacTask)comp.getTask(null, fm, diagListeners[i],
|
||||
Arrays.asList(options[i]), null, Arrays.asList(jfo));
|
||||
if (processors[i] != null) {
|
||||
ct.setProcessors(Collections.singleton(processors[i]));
|
||||
}
|
||||
ct.analyze();
|
||||
}
|
||||
|
||||
//check diags
|
||||
for (Diagnostic<? extends JavaFileObject> diag : diags) {
|
||||
for (DiagnosticProcessor proc : diagProcessors) {
|
||||
if (proc.matches(diag)) {
|
||||
proc.process(diag);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//check all candidates have been used up
|
||||
for (Map.Entry<ElementKey, Candidate> entry : candidatesMap.entrySet()) {
|
||||
if (!seenCandidates.contains(entry.getKey())) {
|
||||
error("Redundant @Candidate annotation on method " + entry.getKey().elem);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
diags.add(diagnostic);
|
||||
}
|
||||
|
||||
Candidate getCandidateAtPos(Element methodSym, long line, long col) {
|
||||
Candidate c = candidatesMap.get(new ElementKey(methodSym));
|
||||
if (c != null) {
|
||||
Pos pos = c.pos();
|
||||
if (!pos.userDefined() ||
|
||||
(pos.line() == line && pos.col() == col)) {
|
||||
seenCandidates.add(new ElementKey(methodSym));
|
||||
return c;
|
||||
}
|
||||
} else {
|
||||
error("Missing @Candidate annotation on method " + methodSym);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void checkSig(Candidate c, Element methodSym, MethodType mtype) {
|
||||
if (c.sig().length() > 0 && !c.sig().equals(mtype.toString())) {
|
||||
error("Inferred type mismatch for method: " + methodSym);
|
||||
}
|
||||
}
|
||||
|
||||
protected void error(String msg) {
|
||||
nerrors++;
|
||||
System.err.printf("Error occurred while checking file: %s\nreason: %s\n", jfo.getName(), msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Base class for diagnostic processor. It provides methods for matching and
|
||||
* processing a given diagnostic object (overridden by subclasses).
|
||||
*/
|
||||
abstract class DiagnosticProcessor {
|
||||
|
||||
List<String> codes;
|
||||
Diagnostic.Kind kind;
|
||||
|
||||
public DiagnosticProcessor(Kind kind, String... codes) {
|
||||
this.codes = Arrays.asList(codes);
|
||||
this.kind = kind;
|
||||
}
|
||||
|
||||
abstract void process(Diagnostic<? extends JavaFileObject> diagnostic);
|
||||
|
||||
boolean matches(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
return (codes.isEmpty() || codes.contains(diagnostic.getCode())) &&
|
||||
diagnostic.getKind() == kind;
|
||||
}
|
||||
|
||||
JCDiagnostic asJCDiagnostic(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
if (diagnostic instanceof JCDiagnostic) {
|
||||
return (JCDiagnostic)diagnostic;
|
||||
} else if (diagnostic instanceof DiagnosticSourceUnwrapper) {
|
||||
return ((DiagnosticSourceUnwrapper)diagnostic).d;
|
||||
} else {
|
||||
throw new AssertionError("Cannot convert diagnostic to JCDiagnostic: " + diagnostic.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
List<JCDiagnostic> subDiagnostics(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
JCDiagnostic diag = asJCDiagnostic(diagnostic);
|
||||
if (diag instanceof JCDiagnostic.MultilineDiagnostic) {
|
||||
return ((JCDiagnostic.MultilineDiagnostic)diag).getSubdiagnostics();
|
||||
} else {
|
||||
throw new AssertionError("Cannot extract subdiagnostics: " + diag.getClass().getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processor for verbose resolution notes generated by javac. The processor
|
||||
* checks that the diagnostic is associated with a method declared by
|
||||
* a class annotated with the special @TraceResolve marker annotation. If
|
||||
* that's the case, all subdiagnostics (one for each resolution candidate)
|
||||
* are checked against the corresponding @Candidate annotations, using
|
||||
* a VerboseCandidateSubdiagProcessor.
|
||||
*/
|
||||
class VerboseResolutionNoteProcessor extends DiagnosticProcessor {
|
||||
|
||||
VerboseResolutionNoteProcessor() {
|
||||
super(Kind.NOTE,
|
||||
"compiler.note.verbose.resolve.multi",
|
||||
"compiler.note.verbose.resolve.multi.1");
|
||||
}
|
||||
|
||||
@Override
|
||||
void process(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
Element siteSym = getSiteSym(diagnostic);
|
||||
if (siteSym.getAnnotation(TraceResolve.class) == null) {
|
||||
return;
|
||||
}
|
||||
int candidateIdx = 0;
|
||||
for (JCDiagnostic d : subDiagnostics(diagnostic)) {
|
||||
boolean isMostSpecific = candidateIdx++ == mostSpecific(diagnostic);
|
||||
VerboseCandidateSubdiagProcessor subProc =
|
||||
new VerboseCandidateSubdiagProcessor(isMostSpecific, phase(diagnostic), success(diagnostic));
|
||||
if (subProc.matches(d)) {
|
||||
subProc.process(d);
|
||||
} else {
|
||||
throw new AssertionError("Bad subdiagnostic: " + d.getCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Element getSiteSym(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
return (Element)asJCDiagnostic(diagnostic).getArgs()[1];
|
||||
}
|
||||
|
||||
int mostSpecific(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
return success(diagnostic) ?
|
||||
(Integer)asJCDiagnostic(diagnostic).getArgs()[2] : -1;
|
||||
}
|
||||
|
||||
boolean success(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
return diagnostic.getCode().equals("compiler.note.verbose.resolve.multi");
|
||||
}
|
||||
|
||||
Phase phase(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
return Phase.fromString(asJCDiagnostic(diagnostic).getArgs()[3].toString());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processor for verbose resolution subdiagnostic notes generated by javac.
|
||||
* The processor checks that the details of the overload candidate
|
||||
* match against the info contained in the corresponding @Candidate
|
||||
* annotation (if any).
|
||||
*/
|
||||
class VerboseCandidateSubdiagProcessor extends DiagnosticProcessor {
|
||||
|
||||
boolean mostSpecific;
|
||||
Phase phase;
|
||||
boolean success;
|
||||
|
||||
public VerboseCandidateSubdiagProcessor(boolean mostSpecific, Phase phase, boolean success) {
|
||||
super(Kind.OTHER,
|
||||
"compiler.misc.applicable.method.found",
|
||||
"compiler.misc.applicable.method.found.1",
|
||||
"compiler.misc.not.applicable.method.found");
|
||||
this.mostSpecific = mostSpecific;
|
||||
this.phase = phase;
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
@Override
|
||||
void process(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
Element methodSym = methodSym(diagnostic);
|
||||
Candidate c = getCandidateAtPos(methodSym,
|
||||
asJCDiagnostic(diagnostic).getLineNumber(),
|
||||
asJCDiagnostic(diagnostic).getColumnNumber());
|
||||
if (c == null) {
|
||||
return; //nothing to check
|
||||
}
|
||||
|
||||
if (c.applicable().length == 0 && c.mostSpecific()) {
|
||||
error("Inapplicable method cannot be most specific " + methodSym);
|
||||
}
|
||||
|
||||
if (isApplicable(diagnostic) != Arrays.asList(c.applicable()).contains(phase)) {
|
||||
error("Invalid candidate's applicability " + methodSym);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
for (Phase p : c.applicable()) {
|
||||
if (phase.ordinal() < p.ordinal()) {
|
||||
error("Invalid phase " + p + " on method " + methodSym);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Arrays.asList(c.applicable()).contains(phase)) { //applicable
|
||||
if (c.mostSpecific() != mostSpecific) {
|
||||
error("Invalid most specific value for method " + methodSym);
|
||||
}
|
||||
MethodType mtype = getSig(diagnostic);
|
||||
if (mtype != null) {
|
||||
checkSig(c, methodSym, mtype);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boolean isApplicable(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
return !diagnostic.getCode().equals("compiler.misc.not.applicable.method.found");
|
||||
}
|
||||
|
||||
Element methodSym(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
return (Element)asJCDiagnostic(diagnostic).getArgs()[1];
|
||||
}
|
||||
|
||||
MethodType getSig(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
JCDiagnostic details = (JCDiagnostic)asJCDiagnostic(diagnostic).getArgs()[2];
|
||||
if (details == null) {
|
||||
return null;
|
||||
} else if (details instanceof JCDiagnostic) {
|
||||
return details.getCode().equals("compiler.misc.full.inst.sig") ?
|
||||
(MethodType)details.getArgs()[0] : null;
|
||||
} else {
|
||||
throw new AssertionError("Bad diagnostic arg: " + details);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processor for verbose deferred inference notes generated by javac. The
|
||||
* processor checks that the inferred signature for a given generic method
|
||||
* call corresponds to the one (if any) declared in the @Candidate annotation.
|
||||
*/
|
||||
class VerboseDeferredInferenceNoteProcessor extends DiagnosticProcessor {
|
||||
|
||||
public VerboseDeferredInferenceNoteProcessor() {
|
||||
super(Kind.NOTE, "compiler.note.deferred.method.inst");
|
||||
}
|
||||
|
||||
@Override
|
||||
void process(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
Element methodSym = methodSym(diagnostic);
|
||||
Candidate c = getCandidateAtPos(methodSym,
|
||||
asJCDiagnostic(diagnostic).getLineNumber(),
|
||||
asJCDiagnostic(diagnostic).getColumnNumber());
|
||||
MethodType sig = sig(diagnostic);
|
||||
if (c != null && sig != null) {
|
||||
checkSig(c, methodSym, sig);
|
||||
}
|
||||
}
|
||||
|
||||
Element methodSym(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
return (Element)asJCDiagnostic(diagnostic).getArgs()[0];
|
||||
}
|
||||
|
||||
MethodType sig(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
return (MethodType)asJCDiagnostic(diagnostic).getArgs()[1];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processor for all error diagnostics; if the error key is not declared in
|
||||
* the test file header, the processor reports an error.
|
||||
*/
|
||||
class ErrorProcessor extends DiagnosticProcessor {
|
||||
|
||||
public ErrorProcessor() {
|
||||
super(Diagnostic.Kind.ERROR);
|
||||
}
|
||||
|
||||
@Override
|
||||
void process(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
if (!declaredKeys.contains(diagnostic.getCode())) {
|
||||
error("Unexpected compilation error key '" + diagnostic.getCode() + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SupportedAnnotationTypes({"Candidate","TraceResolve"})
|
||||
class ResolveCandidateFinder extends JavacTestingAbstractProcessor {
|
||||
|
||||
@Override
|
||||
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
|
||||
if (roundEnv.processingOver())
|
||||
return true;
|
||||
|
||||
TypeElement traceResolveAnno = elements.getTypeElement("TraceResolve");
|
||||
TypeElement candidateAnno = elements.getTypeElement("Candidate");
|
||||
|
||||
if (!annotations.contains(traceResolveAnno)) {
|
||||
error("no @TraceResolve annotation found in test class");
|
||||
}
|
||||
|
||||
if (!annotations.contains(candidateAnno)) {
|
||||
error("no @candidate annotation found in test class");
|
||||
}
|
||||
|
||||
for (Element elem: roundEnv.getElementsAnnotatedWith(traceResolveAnno)) {
|
||||
TraceResolve traceResolve = elem.getAnnotation(TraceResolve.class);
|
||||
declaredKeys.addAll(Arrays.asList(traceResolve.keys()));
|
||||
}
|
||||
|
||||
for (Element elem: roundEnv.getElementsAnnotatedWith(candidateAnno)) {
|
||||
candidatesMap.put(new ElementKey(elem), elem.getAnnotation(Candidate.class));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class ElementKey {
|
||||
|
||||
String key;
|
||||
Element elem;
|
||||
|
||||
public ElementKey(Element elem) {
|
||||
this.elem = elem;
|
||||
this.key = computeKey(elem);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof ElementKey) {
|
||||
ElementKey other = (ElementKey)obj;
|
||||
return other.key.equals(key);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return key.hashCode();
|
||||
}
|
||||
|
||||
String computeKey(Element e) {
|
||||
StringBuilder buf = new StringBuilder();
|
||||
while (e != null) {
|
||||
buf.append(e.toString());
|
||||
e = e.getEnclosingElement();
|
||||
}
|
||||
buf.append(jfo.getName());
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Key{"+key+"}";
|
||||
}
|
||||
}
|
||||
|
||||
class DiagnosticHandler implements DiagnosticListener<JavaFileObject> {
|
||||
|
||||
boolean shouldRecordDiags;
|
||||
|
||||
DiagnosticHandler(boolean shouldRecordDiags) {
|
||||
this.shouldRecordDiags = shouldRecordDiags;
|
||||
}
|
||||
|
||||
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
if (shouldRecordDiags)
|
||||
diags.add(diagnostic);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
29
langtools/test/tools/javac/resolve/TraceResolve.java
Normal file
29
langtools/test/tools/javac/resolve/TraceResolve.java
Normal file
@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.TYPE)
|
||||
@interface TraceResolve {
|
||||
String[] keys() default {};
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
@TraceResolve
|
||||
class BoxedReturnTypeInference {
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Byte", mostSpecific=true)
|
||||
static <B> B m_byte() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Short", mostSpecific=true)
|
||||
static <S> S m_short() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Integer", mostSpecific=true)
|
||||
static <I> I m_int() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Long", mostSpecific=true)
|
||||
static <L> L m_long() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Float", mostSpecific=true)
|
||||
static <F> F m_float() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Double", mostSpecific=true)
|
||||
static <D> D m_double() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Character", mostSpecific=true)
|
||||
static <C> C m_char() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Boolean", mostSpecific=true)
|
||||
static <Z> Z m_bool() { return null; }
|
||||
|
||||
{
|
||||
Byte b = m_byte();
|
||||
Short s = m_short();
|
||||
Integer i = m_int();
|
||||
Long l = m_long();
|
||||
Float f = m_float();
|
||||
Double d = m_double();
|
||||
Character c= m_char();
|
||||
Boolean z = m_bool();
|
||||
}
|
||||
}
|
@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
@TraceResolve
|
||||
class PrimitiveOverReference {
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_byte(byte b) {}
|
||||
@Candidate
|
||||
static void m_byte(Byte b) {}
|
||||
@Candidate
|
||||
static <B> void m_byte(B b) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_short(short s) {}
|
||||
@Candidate
|
||||
static void m_short(Short s) {}
|
||||
@Candidate
|
||||
static <S> void m_short(S s) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_int(int i) {}
|
||||
@Candidate
|
||||
static void m_int(Integer i) {}
|
||||
@Candidate
|
||||
static <I> void m_int(I i) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_long(long l) {}
|
||||
@Candidate
|
||||
static void m_long(Long l) {}
|
||||
@Candidate
|
||||
static <L> void m_long(L l) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_float(float f) {}
|
||||
@Candidate
|
||||
static void m_float(Float f) {}
|
||||
@Candidate
|
||||
static <F> void m_float(F f) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_double(double d) {}
|
||||
@Candidate
|
||||
static void m_double(Double d) {}
|
||||
@Candidate
|
||||
static <D> void m_double(D d) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_char(char c) {}
|
||||
@Candidate
|
||||
static void m_char(Character c) {}
|
||||
@Candidate
|
||||
static <C> void m_char(C c) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_bool(boolean z) {}
|
||||
@Candidate
|
||||
static void m_bool(Boolean z) {}
|
||||
@Candidate
|
||||
static <Z> void m_bool(Z z) {}
|
||||
|
||||
{
|
||||
m_byte((byte)0);
|
||||
m_short((short)0);
|
||||
m_int(0);
|
||||
m_long(0L);
|
||||
m_float(0.0f);
|
||||
m_double(0.0);
|
||||
m_char('?');
|
||||
m_bool(false);
|
||||
}
|
||||
}
|
@ -0,0 +1,108 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
@TraceResolve
|
||||
class PrimitiveOverReference {
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_byte(byte b) {}
|
||||
@Candidate
|
||||
static void m_byte(Byte b) {}
|
||||
@Candidate
|
||||
static void m_byte(byte... b) {}
|
||||
@Candidate
|
||||
static void m_byte(Byte... b) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_short(short s) {}
|
||||
@Candidate
|
||||
static void m_short(Short s) {}
|
||||
@Candidate
|
||||
static void m_short(short... s) {}
|
||||
@Candidate
|
||||
static void m_short(Short... s) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_int(int i) {}
|
||||
@Candidate
|
||||
static void m_int(Integer i) {}
|
||||
@Candidate
|
||||
static void m_int(int... i) {}
|
||||
@Candidate
|
||||
static void m_int(Integer... i) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_long(long l) {}
|
||||
@Candidate
|
||||
static void m_long(Long l) {}
|
||||
@Candidate
|
||||
static void m_long(long... l) {}
|
||||
@Candidate
|
||||
static void m_long(Long... l) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_float(float f) {}
|
||||
@Candidate
|
||||
static void m_float(Float f) {}
|
||||
@Candidate
|
||||
static void m_float(float... f) {}
|
||||
@Candidate
|
||||
static void m_float(Float... f) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_double(double d) {}
|
||||
@Candidate
|
||||
static void m_double(Double d) {}
|
||||
@Candidate
|
||||
static void m_double(double... d) {}
|
||||
@Candidate
|
||||
static void m_double(Double... d) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_char(char c) {}
|
||||
@Candidate
|
||||
static void m_char(Character c) {}
|
||||
@Candidate
|
||||
static void m_char(char... c) {}
|
||||
@Candidate
|
||||
static void m_char(Character... c) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_bool(boolean z) {}
|
||||
@Candidate
|
||||
static void m_bool(Boolean z) {}
|
||||
@Candidate
|
||||
static void m_bool(boolean... z) {}
|
||||
@Candidate
|
||||
static void m_bool(Boolean... z) {}
|
||||
|
||||
{
|
||||
m_byte((byte)0);
|
||||
m_short((short)0);
|
||||
m_int(0);
|
||||
m_long(0L);
|
||||
m_float(0.0f);
|
||||
m_double(0.0);
|
||||
m_char('?');
|
||||
m_bool(false);
|
||||
}
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
@TraceResolve(keys={"compiler.err.ref.ambiguous"})
|
||||
class PrimitiveOverReferenceVarargsAmbiguous {
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_byte(byte... b) {}
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_byte(Byte... b) {}
|
||||
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_short(short... s) {}
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_short(Short... s) {}
|
||||
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_int(int... i) {}
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_int(Integer... i) {}
|
||||
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_long(long... l) {}
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_long(Long... l) {}
|
||||
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_float(float... f) {}
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_float(Float... f) {}
|
||||
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_double(double... d) {}
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_double(Double... d) {}
|
||||
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_char(char... c) {}
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_char(Character... c) {}
|
||||
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_bool(boolean... z) {}
|
||||
@Candidate(applicable=Phase.VARARGS, mostSpecific=false)
|
||||
static void m_bool(Boolean... z) {}
|
||||
|
||||
{
|
||||
m_byte((byte)0);
|
||||
m_short((short)0);
|
||||
m_int(0);
|
||||
m_long(0L);
|
||||
m_float(0.0f);
|
||||
m_double(0.0);
|
||||
m_char('?');
|
||||
m_bool(false);
|
||||
}
|
||||
}
|
113
langtools/test/tools/javac/resolve/tests/PrimitiveOverload.java
Normal file
113
langtools/test/tools/javac/resolve/tests/PrimitiveOverload.java
Normal file
@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
@TraceResolve
|
||||
class PrimitiveOverload {
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_byte(byte b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_byte(short b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_byte(int b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_byte(long b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_byte(float b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_byte(double b) {}
|
||||
|
||||
@Candidate
|
||||
static void m_short(byte b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_short(short b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_short(int b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_short(long b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_short(float b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_short(double b) {}
|
||||
|
||||
@Candidate
|
||||
static void m_int(byte b) {}
|
||||
@Candidate
|
||||
static void m_int(short b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_int(int b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_int(long b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_int(float b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_int(double b) {}
|
||||
|
||||
@Candidate
|
||||
static void m_long(byte b) {}
|
||||
@Candidate
|
||||
static void m_long(short b) {}
|
||||
@Candidate
|
||||
static void m_long(int b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_long(long b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_long(float b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_long(double b) {}
|
||||
|
||||
@Candidate
|
||||
static void m_float(byte b) {}
|
||||
@Candidate
|
||||
static void m_float(short b) {}
|
||||
@Candidate
|
||||
static void m_float(int b) {}
|
||||
@Candidate
|
||||
static void m_float(long b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_float(float b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_float(double b) {}
|
||||
|
||||
@Candidate
|
||||
static void m_double(byte b) {}
|
||||
@Candidate
|
||||
static void m_double(short b) {}
|
||||
@Candidate
|
||||
static void m_double(int b) {}
|
||||
@Candidate
|
||||
static void m_double(long b) {}
|
||||
@Candidate
|
||||
static void m_double(float b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_double(double b) {}
|
||||
|
||||
{
|
||||
m_byte((byte)0);
|
||||
m_short((short)0);
|
||||
m_int(0);
|
||||
m_long(0L);
|
||||
m_float(0.0f);
|
||||
m_double(0.0);
|
||||
}
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
@TraceResolve
|
||||
class PrimitiveReturnTypeInference {
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Byte", mostSpecific=true)
|
||||
static <B> B m_byte() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Short", mostSpecific=true)
|
||||
static <S> S m_short() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Integer", mostSpecific=true)
|
||||
static <I> I m_int() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Long", mostSpecific=true)
|
||||
static <L> L m_long() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Float", mostSpecific=true)
|
||||
static <F> F m_float() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Double", mostSpecific=true)
|
||||
static <D> D m_double() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Character", mostSpecific=true)
|
||||
static <C> C m_char() { return null; }
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, sig="()java.lang.Boolean", mostSpecific=true)
|
||||
static <Z> Z m_bool() { return null; }
|
||||
|
||||
{
|
||||
byte b = m_byte();
|
||||
short s = m_short();
|
||||
int i = m_int();
|
||||
long l = m_long();
|
||||
float f = m_float();
|
||||
double d = m_double();
|
||||
char c= m_char();
|
||||
boolean z = m_bool();
|
||||
}
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
@TraceResolve
|
||||
class PrimitiveOverInferred {
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_byte(Byte b) {}
|
||||
@Candidate(applicable=Phase.BOX, sig="(java.lang.Byte)void")
|
||||
static <B> void m_byte(B b) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_short(Short s) {}
|
||||
@Candidate(applicable=Phase.BOX, sig="(java.lang.Short)void")
|
||||
static <S> void m_short(S s) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_int(Integer i) {}
|
||||
@Candidate(applicable=Phase.BOX, sig="(java.lang.Integer)void")
|
||||
static <I> void m_int(I i) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_long(Long l) {}
|
||||
@Candidate(applicable=Phase.BOX, sig="(java.lang.Long)void")
|
||||
static <L> void m_long(L l) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_float(Float f) {}
|
||||
@Candidate(applicable=Phase.BOX, sig="(java.lang.Float)void")
|
||||
static <F> void m_float(F f) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_double(Double d) {}
|
||||
@Candidate(applicable=Phase.BOX, sig="(java.lang.Double)void")
|
||||
static <D> void m_double(D d) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_char(Character c) {}
|
||||
@Candidate(applicable=Phase.BOX, sig="(java.lang.Character)void")
|
||||
static <C> void m_char(C c) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_bool(Boolean z) {}
|
||||
@Candidate(applicable=Phase.BOX, sig="(java.lang.Boolean)void")
|
||||
static <Z> void m_bool(Z z) {}
|
||||
|
||||
{
|
||||
m_byte((byte)0);
|
||||
m_short((short)0);
|
||||
m_int(0);
|
||||
m_long(0L);
|
||||
m_float(0.0f);
|
||||
m_double(0.0);
|
||||
m_char('?');
|
||||
m_bool(false);
|
||||
}
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
@TraceResolve
|
||||
class ReferenceOverVarargs {
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_byte(Byte b) {}
|
||||
@Candidate
|
||||
static void m_byte(byte... b) {}
|
||||
@Candidate
|
||||
static void m_byte(Byte... b) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_short(Short s) {}
|
||||
@Candidate
|
||||
static void m_short(short... s) {}
|
||||
@Candidate
|
||||
static void m_short(Short... s) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_int(Integer i) {}
|
||||
@Candidate
|
||||
static void m_int(int... i) {}
|
||||
@Candidate
|
||||
static void m_int(Integer... i) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_long(Long l) {}
|
||||
@Candidate
|
||||
static void m_long(long... l) {}
|
||||
@Candidate
|
||||
static void m_long(Long... l) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_float(Float f) {}
|
||||
@Candidate
|
||||
static void m_float(float... f) {}
|
||||
@Candidate
|
||||
static void m_float(Float... f) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_double(Double d) {}
|
||||
@Candidate
|
||||
static void m_double(double... d) {}
|
||||
@Candidate
|
||||
static void m_double(Double... d) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_char(Character c) {}
|
||||
@Candidate
|
||||
static void m_char(char... c) {}
|
||||
@Candidate
|
||||
static void m_char(Character... c) {}
|
||||
|
||||
@Candidate(applicable=Phase.BOX, mostSpecific=true)
|
||||
static void m_bool(Boolean z) {}
|
||||
@Candidate
|
||||
static void m_bool(boolean... z) {}
|
||||
@Candidate
|
||||
static void m_bool(Boolean... z) {}
|
||||
|
||||
{
|
||||
m_byte((byte)0);
|
||||
m_short((short)0);
|
||||
m_int(0);
|
||||
m_long(0L);
|
||||
m_float(0.0f);
|
||||
m_double(0.0);
|
||||
m_char('?');
|
||||
m_bool(false);
|
||||
}
|
||||
}
|
@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
@TraceResolve
|
||||
class ReferenceOverload {
|
||||
|
||||
static class A {}
|
||||
static class B extends A {}
|
||||
static class C extends B {}
|
||||
static class D extends C {}
|
||||
static class E extends D {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_A(A a) {}
|
||||
@Candidate
|
||||
static void m_A(B a) {}
|
||||
@Candidate
|
||||
static void m_A(C a) {}
|
||||
@Candidate
|
||||
static void m_A(D a) {}
|
||||
@Candidate
|
||||
static void m_A(E a) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_B(A b) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_B(B b) {}
|
||||
@Candidate
|
||||
static void m_B(C b) {}
|
||||
@Candidate
|
||||
static void m_B(D b) {}
|
||||
@Candidate
|
||||
static void m_B(E b) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_C(A c) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_C(B c) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_C(C c) {}
|
||||
@Candidate
|
||||
static void m_C(D c) {}
|
||||
@Candidate
|
||||
static void m_C(E c) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_D(A d) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_D(B d) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_D(C d) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_D(D d) {}
|
||||
@Candidate
|
||||
static void m_D(E d) {}
|
||||
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_E(A e) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_E(B e) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_E(C e) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=false)
|
||||
static void m_E(D e) {}
|
||||
@Candidate(applicable=Phase.BASIC, mostSpecific=true)
|
||||
static void m_E(E e) {}
|
||||
|
||||
{
|
||||
m_A((A)null);
|
||||
m_B((B)null);
|
||||
m_C((C)null);
|
||||
m_D((D)null);
|
||||
m_E((E)null);
|
||||
}
|
||||
}
|
196
langtools/test/tools/javac/tree/DocCommentToplevelTest.java
Normal file
196
langtools/test/tools/javac/tree/DocCommentToplevelTest.java
Normal file
@ -0,0 +1,196 @@
|
||||
/*
|
||||
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 7096014
|
||||
* @summary Javac tokens should retain state
|
||||
*/
|
||||
|
||||
import com.sun.source.tree.*;
|
||||
import com.sun.source.util.*;
|
||||
import com.sun.tools.javac.tree.JCTree;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.*;
|
||||
import javax.tools.*;
|
||||
|
||||
|
||||
public class DocCommentToplevelTest {
|
||||
|
||||
enum PackageKind {
|
||||
HAS_PKG("package pkg;"),
|
||||
NO_PKG("");
|
||||
|
||||
String pkgStr;
|
||||
|
||||
PackageKind(String pkgStr) {
|
||||
this.pkgStr = pkgStr;
|
||||
}
|
||||
}
|
||||
|
||||
enum ImportKind {
|
||||
ZERO(""),
|
||||
ONE("import java.lang.*;"),
|
||||
TWO("import java.lang.*; import java.util.*;");
|
||||
|
||||
String importStr;
|
||||
|
||||
ImportKind(String importStr) {
|
||||
this.importStr = importStr;
|
||||
}
|
||||
}
|
||||
|
||||
enum ModifierKind {
|
||||
DEFAULT(""),
|
||||
PUBLIC("public");
|
||||
|
||||
String modStr;
|
||||
|
||||
ModifierKind(String modStr) {
|
||||
this.modStr = modStr;
|
||||
}
|
||||
}
|
||||
|
||||
enum ToplevelDocKind {
|
||||
HAS_DOC("/** Toplevel! */"),
|
||||
NO_DOC("");
|
||||
|
||||
String docStr;
|
||||
|
||||
ToplevelDocKind(String docStr) {
|
||||
this.docStr = docStr;
|
||||
}
|
||||
}
|
||||
|
||||
static int errors;
|
||||
static int checks;
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
//create default shared JavaCompiler - reused across multiple compilations
|
||||
JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
|
||||
StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
|
||||
|
||||
for (PackageKind pk : PackageKind.values()) {
|
||||
for (ImportKind ik : ImportKind.values()) {
|
||||
for (ModifierKind mk1 : ModifierKind.values()) {
|
||||
for (ModifierKind mk2 : ModifierKind.values()) {
|
||||
for (ToplevelDocKind tdk : ToplevelDocKind.values()) {
|
||||
new DocCommentToplevelTest(pk, ik, mk1, mk2, tdk).run(comp, fm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (errors > 0)
|
||||
throw new AssertionError(errors + " errors found");
|
||||
|
||||
System.out.println(checks + " checks were made");
|
||||
}
|
||||
|
||||
PackageKind pk;
|
||||
ImportKind ik;
|
||||
ModifierKind mk1;
|
||||
ModifierKind mk2;
|
||||
ToplevelDocKind tdk;
|
||||
JavaSource source;
|
||||
|
||||
DocCommentToplevelTest(PackageKind pk, ImportKind ik, ModifierKind mk1, ModifierKind mk2, ToplevelDocKind tdk) {
|
||||
this.pk = pk;
|
||||
this.ik = ik;
|
||||
this.mk1 = mk1;
|
||||
this.mk2 = mk2;
|
||||
this.tdk = tdk;
|
||||
source = new JavaSource();
|
||||
}
|
||||
|
||||
void run(JavaCompiler comp, JavaFileManager fm) throws Exception {
|
||||
JavacTask task = (JavacTask)comp.getTask(null, fm, null, Arrays.asList("-printsource"), null, Arrays.asList(source));
|
||||
for (CompilationUnitTree cu: task.parse()) {
|
||||
check(cu);
|
||||
}
|
||||
}
|
||||
|
||||
void check(CompilationUnitTree cu) {
|
||||
checks++;
|
||||
|
||||
new TreeScanner<ClassTree,Void>() {
|
||||
|
||||
Map<JCTree, String> docComments;
|
||||
|
||||
@Override
|
||||
public ClassTree visitCompilationUnit(CompilationUnitTree node, Void unused) {
|
||||
docComments = ((JCTree.JCCompilationUnit)node).docComments;
|
||||
boolean expectedComment = tdk == ToplevelDocKind.HAS_DOC &&
|
||||
(pk != PackageKind.NO_PKG || ik != ImportKind.ZERO);
|
||||
boolean foundComment = docComments.get(node) != null;
|
||||
if (expectedComment != foundComment) {
|
||||
error("Unexpected comment " + docComments.get(node) + " on toplevel");
|
||||
}
|
||||
return super.visitCompilationUnit(node, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ClassTree visitClass(ClassTree node, Void unused) {
|
||||
boolean expectedComment = tdk == ToplevelDocKind.HAS_DOC &&
|
||||
pk == PackageKind.NO_PKG && ik == ImportKind.ZERO &&
|
||||
node.getSimpleName().toString().equals("First");
|
||||
boolean foundComment = docComments.get(node) != null;
|
||||
if (expectedComment != foundComment) {
|
||||
error("Unexpected comment " + docComments.get(node) + " on class " + node.getSimpleName());
|
||||
}
|
||||
return super.visitClass(node, unused);
|
||||
}
|
||||
}.scan(cu, null);
|
||||
}
|
||||
|
||||
void error(String msg) {
|
||||
System.err.println("Error: " + msg);
|
||||
System.err.println("Source: " + source.source);
|
||||
errors++;
|
||||
}
|
||||
|
||||
class JavaSource extends SimpleJavaFileObject {
|
||||
|
||||
String template = "#D\n#P\n#I\n" +
|
||||
"#M1 class First { }\n" +
|
||||
"#M2 class Second { }\n";
|
||||
|
||||
String source;
|
||||
|
||||
public JavaSource() {
|
||||
super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
|
||||
source = template.replace("#P", pk.pkgStr)
|
||||
.replace("#I", ik.importStr)
|
||||
.replace("#M1", mk1.modStr)
|
||||
.replace("#M2", mk2.modStr)
|
||||
.replace("#D", tdk.docStr);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
|
||||
return source;
|
||||
}
|
||||
}
|
||||
}
|
18
langtools/test/tools/javac/varargs/7097436/T7097436.java
Normal file
18
langtools/test/tools/javac/varargs/7097436/T7097436.java
Normal file
@ -0,0 +1,18 @@
|
||||
/*
|
||||
* @test /nodynamiccopyright/
|
||||
* @bug 7097436
|
||||
* @summary ClassCastException occurs in assignment expressions without any heap pollutions
|
||||
* @compile/fail/ref=T7097436.out -Xlint:varargs -Werror -XDrawDiagnostics T7097436.java
|
||||
*/
|
||||
|
||||
import java.util.List;
|
||||
|
||||
class T7097436 {
|
||||
@SafeVarargs
|
||||
static void m(List<String>... ls) {
|
||||
Object o = ls; //warning
|
||||
Object[] oArr = ls; //warning
|
||||
String s = ls; // no warning
|
||||
Integer[] iArr = ls; // no warning
|
||||
}
|
||||
}
|
6
langtools/test/tools/javac/varargs/7097436/T7097436.out
Normal file
6
langtools/test/tools/javac/varargs/7097436/T7097436.out
Normal file
@ -0,0 +1,6 @@
|
||||
T7097436.java:13:20: compiler.warn.varargs.unsafe.use.varargs.param: ls
|
||||
T7097436.java:14:25: compiler.warn.varargs.unsafe.use.varargs.param: ls
|
||||
T7097436.java:15:20: compiler.err.prob.found.req: (compiler.misc.incompatible.types), java.util.List<java.lang.String>[], java.lang.String
|
||||
T7097436.java:16:26: compiler.err.prob.found.req: (compiler.misc.incompatible.types), java.util.List<java.lang.String>[], java.lang.Integer[]
|
||||
2 errors
|
||||
2 warnings
|
@ -23,7 +23,7 @@
|
||||
|
||||
/**
|
||||
* @test
|
||||
* @bug 6993978
|
||||
* @bug 6993978 7097436
|
||||
* @summary Project Coin: Annotation to reduce varargs warnings
|
||||
* @author mcimadamore
|
||||
* @run main Warn5
|
||||
@ -31,8 +31,8 @@
|
||||
import com.sun.source.util.JavacTask;
|
||||
import com.sun.tools.javac.api.JavacTool;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumSet;
|
||||
import javax.tools.Diagnostic;
|
||||
import javax.tools.JavaCompiler;
|
||||
import javax.tools.JavaFileObject;
|
||||
@ -95,7 +95,6 @@ public class Warn5 {
|
||||
METHOD("void m"),
|
||||
CONSTRUCTOR("Test");
|
||||
|
||||
|
||||
String name;
|
||||
|
||||
MethodKind(String name) {
|
||||
@ -155,7 +154,124 @@ public class Warn5 {
|
||||
}
|
||||
}
|
||||
|
||||
static class JavaSource extends SimpleJavaFileObject {
|
||||
enum WarningKind {
|
||||
UNSAFE_BODY,
|
||||
UNSAFE_DECL,
|
||||
MALFORMED_SAFEVARARGS,
|
||||
REDUNDANT_SAFEVARARGS;
|
||||
}
|
||||
|
||||
// Create a single file manager and reuse it for each compile to save time.
|
||||
static StandardJavaFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
for (SourceLevel sourceLevel : SourceLevel.values()) {
|
||||
for (XlintOption xlint : XlintOption.values()) {
|
||||
for (TrustMe trustMe : TrustMe.values()) {
|
||||
for (SuppressLevel suppressLevel : SuppressLevel.values()) {
|
||||
for (ModifierKind modKind : ModifierKind.values()) {
|
||||
for (MethodKind methKind : MethodKind.values()) {
|
||||
for (SignatureKind sig : SignatureKind.values()) {
|
||||
for (BodyKind body : BodyKind.values()) {
|
||||
new Warn5(sourceLevel,
|
||||
xlint,
|
||||
trustMe,
|
||||
suppressLevel,
|
||||
modKind,
|
||||
methKind,
|
||||
sig,
|
||||
body).test();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final SourceLevel sourceLevel;
|
||||
final XlintOption xlint;
|
||||
final TrustMe trustMe;
|
||||
final SuppressLevel suppressLevel;
|
||||
final ModifierKind modKind;
|
||||
final MethodKind methKind;
|
||||
final SignatureKind sig;
|
||||
final BodyKind body;
|
||||
final JavaSource source;
|
||||
final DiagnosticChecker dc;
|
||||
|
||||
public Warn5(SourceLevel sourceLevel, XlintOption xlint, TrustMe trustMe, SuppressLevel suppressLevel, ModifierKind modKind, MethodKind methKind, SignatureKind sig, BodyKind body) {
|
||||
this.sourceLevel = sourceLevel;
|
||||
this.xlint = xlint;
|
||||
this.trustMe = trustMe;
|
||||
this.suppressLevel = suppressLevel;
|
||||
this.modKind = modKind;
|
||||
this.methKind = methKind;
|
||||
this.sig = sig;
|
||||
this.body = body;
|
||||
this.source = new JavaSource();
|
||||
this.dc = new DiagnosticChecker();
|
||||
}
|
||||
|
||||
void test() throws Exception {
|
||||
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
|
||||
JavacTask ct = (JavacTask)tool.getTask(null, fm, dc,
|
||||
Arrays.asList(xlint.getXlintOption(), "-source", sourceLevel.sourceKey), null, Arrays.asList(source));
|
||||
ct.analyze();
|
||||
check();
|
||||
}
|
||||
|
||||
void check() {
|
||||
|
||||
EnumSet<WarningKind> expectedWarnings = EnumSet.noneOf(WarningKind.class);
|
||||
|
||||
if (sourceLevel == SourceLevel.JDK_7 &&
|
||||
trustMe == TrustMe.TRUST &&
|
||||
suppressLevel != SuppressLevel.VARARGS &&
|
||||
xlint != XlintOption.NONE &&
|
||||
sig.isVarargs && !sig.isReifiableArg && body.hasAliasing &&
|
||||
(methKind == MethodKind.CONSTRUCTOR || (methKind == MethodKind.METHOD && modKind != ModifierKind.NONE))) {
|
||||
expectedWarnings.add(WarningKind.UNSAFE_BODY);
|
||||
}
|
||||
|
||||
if (sourceLevel == SourceLevel.JDK_7 &&
|
||||
trustMe == TrustMe.DONT_TRUST &&
|
||||
sig.isVarargs &&
|
||||
!sig.isReifiableArg &&
|
||||
xlint == XlintOption.ALL) {
|
||||
expectedWarnings.add(WarningKind.UNSAFE_DECL);
|
||||
}
|
||||
|
||||
if (sourceLevel == SourceLevel.JDK_7 &&
|
||||
trustMe == TrustMe.TRUST &&
|
||||
(!sig.isVarargs ||
|
||||
(modKind == ModifierKind.NONE && methKind == MethodKind.METHOD))) {
|
||||
expectedWarnings.add(WarningKind.MALFORMED_SAFEVARARGS);
|
||||
}
|
||||
|
||||
if (sourceLevel == SourceLevel.JDK_7 &&
|
||||
trustMe == TrustMe.TRUST &&
|
||||
xlint != XlintOption.NONE &&
|
||||
suppressLevel != SuppressLevel.VARARGS &&
|
||||
(modKind != ModifierKind.NONE || methKind == MethodKind.CONSTRUCTOR) &&
|
||||
sig.isVarargs &&
|
||||
sig.isReifiableArg) {
|
||||
expectedWarnings.add(WarningKind.REDUNDANT_SAFEVARARGS);
|
||||
}
|
||||
|
||||
if (!expectedWarnings.containsAll(dc.warnings) ||
|
||||
!dc.warnings.containsAll(expectedWarnings)) {
|
||||
throw new Error("invalid diagnostics for source:\n" +
|
||||
source.getCharContent(true) +
|
||||
"\nOptions: " + xlint.getXlintOption() +
|
||||
"\nExpected warnings: " + expectedWarnings +
|
||||
"\nFound warnings: " + dc.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
class JavaSource extends SimpleJavaFileObject {
|
||||
|
||||
String template = "import com.sun.tools.javac.api.*;\n" +
|
||||
"import java.util.List;\n" +
|
||||
@ -167,12 +283,11 @@ public class Warn5 {
|
||||
|
||||
String source;
|
||||
|
||||
public JavaSource(TrustMe trustMe, SuppressLevel suppressLevel, ModifierKind modKind,
|
||||
MethodKind methKind, SignatureKind meth, BodyKind body) {
|
||||
public JavaSource() {
|
||||
super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
|
||||
source = template.replace("#T", trustMe.anno).
|
||||
replace("#S", suppressLevel.getSuppressAnno()).
|
||||
replace("#M", meth.getSignature(modKind, methKind)).
|
||||
replace("#M", sig.getSignature(modKind, methKind)).
|
||||
replace("#B", body.body);
|
||||
}
|
||||
|
||||
@ -182,117 +297,34 @@ public class Warn5 {
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
for (SourceLevel sourceLevel : SourceLevel.values()) {
|
||||
for (XlintOption xlint : XlintOption.values()) {
|
||||
for (TrustMe trustMe : TrustMe.values()) {
|
||||
for (SuppressLevel suppressLevel : SuppressLevel.values()) {
|
||||
for (ModifierKind modKind : ModifierKind.values()) {
|
||||
for (MethodKind methKind : MethodKind.values()) {
|
||||
for (SignatureKind sig : SignatureKind.values()) {
|
||||
for (BodyKind body : BodyKind.values()) {
|
||||
test(sourceLevel,
|
||||
xlint,
|
||||
trustMe,
|
||||
suppressLevel,
|
||||
modKind,
|
||||
methKind,
|
||||
sig,
|
||||
body);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
|
||||
|
||||
// Create a single file manager and reuse it for each compile to save time.
|
||||
static StandardJavaFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);
|
||||
|
||||
static void test(SourceLevel sourceLevel, XlintOption xlint, TrustMe trustMe, SuppressLevel suppressLevel,
|
||||
ModifierKind modKind, MethodKind methKind, SignatureKind sig, BodyKind body) throws Exception {
|
||||
final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
|
||||
JavaSource source = new JavaSource(trustMe, suppressLevel, modKind, methKind, sig, body);
|
||||
DiagnosticChecker dc = new DiagnosticChecker();
|
||||
JavacTask ct = (JavacTask)tool.getTask(null, fm, dc,
|
||||
Arrays.asList(xlint.getXlintOption(), "-source", sourceLevel.sourceKey), null, Arrays.asList(source));
|
||||
ct.analyze();
|
||||
check(sourceLevel, dc, source, xlint, trustMe,
|
||||
suppressLevel, modKind, methKind, sig, body);
|
||||
}
|
||||
|
||||
static void check(SourceLevel sourceLevel, DiagnosticChecker dc, JavaSource source,
|
||||
XlintOption xlint, TrustMe trustMe, SuppressLevel suppressLevel, ModifierKind modKind,
|
||||
MethodKind methKind, SignatureKind meth, BodyKind body) {
|
||||
|
||||
boolean hasPotentiallyUnsafeBody = sourceLevel == SourceLevel.JDK_7 &&
|
||||
trustMe == TrustMe.TRUST &&
|
||||
suppressLevel != SuppressLevel.VARARGS &&
|
||||
xlint != XlintOption.NONE &&
|
||||
meth.isVarargs && !meth.isReifiableArg && body.hasAliasing &&
|
||||
(methKind == MethodKind.CONSTRUCTOR || (methKind == MethodKind.METHOD && modKind != ModifierKind.NONE));
|
||||
|
||||
boolean hasPotentiallyPollutingDecl = sourceLevel == SourceLevel.JDK_7 &&
|
||||
trustMe == TrustMe.DONT_TRUST &&
|
||||
meth.isVarargs &&
|
||||
!meth.isReifiableArg &&
|
||||
xlint == XlintOption.ALL;
|
||||
|
||||
boolean hasMalformedAnnoInDecl = sourceLevel == SourceLevel.JDK_7 &&
|
||||
trustMe == TrustMe.TRUST &&
|
||||
(!meth.isVarargs ||
|
||||
(modKind == ModifierKind.NONE && methKind == MethodKind.METHOD));
|
||||
|
||||
boolean hasRedundantAnnoInDecl = sourceLevel == SourceLevel.JDK_7 &&
|
||||
trustMe == TrustMe.TRUST &&
|
||||
xlint != XlintOption.NONE &&
|
||||
suppressLevel != SuppressLevel.VARARGS &&
|
||||
(modKind != ModifierKind.NONE || methKind == MethodKind.CONSTRUCTOR) &&
|
||||
meth.isVarargs &&
|
||||
meth.isReifiableArg;
|
||||
|
||||
if (hasPotentiallyUnsafeBody != dc.hasPotentiallyUnsafeBody ||
|
||||
hasPotentiallyPollutingDecl != dc.hasPotentiallyPollutingDecl ||
|
||||
hasMalformedAnnoInDecl != dc.hasMalformedAnnoInDecl ||
|
||||
hasRedundantAnnoInDecl != dc.hasRedundantAnnoInDecl) {
|
||||
throw new Error("invalid diagnostics for source:\n" +
|
||||
source.getCharContent(true) +
|
||||
"\nOptions: " + xlint.getXlintOption() +
|
||||
"\nExpected potentially unsafe body warning: " + hasPotentiallyUnsafeBody +
|
||||
"\nExpected potentially polluting decl warning: " + hasPotentiallyPollutingDecl +
|
||||
"\nExpected malformed anno error: " + hasMalformedAnnoInDecl +
|
||||
"\nExpected redundant anno warning: " + hasRedundantAnnoInDecl +
|
||||
"\nFound potentially unsafe body warning: " + dc.hasPotentiallyUnsafeBody +
|
||||
"\nFound potentially polluting decl warning: " + dc.hasPotentiallyPollutingDecl +
|
||||
"\nFound malformed anno error: " + dc.hasMalformedAnnoInDecl +
|
||||
"\nFound redundant anno warning: " + dc.hasRedundantAnnoInDecl);
|
||||
}
|
||||
}
|
||||
|
||||
static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
|
||||
|
||||
boolean hasPotentiallyUnsafeBody = false;
|
||||
boolean hasPotentiallyPollutingDecl = false;
|
||||
boolean hasMalformedAnnoInDecl = false;
|
||||
boolean hasRedundantAnnoInDecl = false;
|
||||
EnumSet<WarningKind> warnings = EnumSet.noneOf(WarningKind.class);
|
||||
|
||||
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
|
||||
if (diagnostic.getKind() == Diagnostic.Kind.WARNING) {
|
||||
if (diagnostic.getCode().contains("unsafe.use.varargs.param")) {
|
||||
hasPotentiallyUnsafeBody = true;
|
||||
setWarning(WarningKind.UNSAFE_BODY);
|
||||
} else if (diagnostic.getCode().contains("redundant.trustme")) {
|
||||
hasRedundantAnnoInDecl = true;
|
||||
setWarning(WarningKind.REDUNDANT_SAFEVARARGS);
|
||||
}
|
||||
} else if (diagnostic.getKind() == Diagnostic.Kind.MANDATORY_WARNING &&
|
||||
diagnostic.getCode().contains("varargs.non.reifiable.type")) {
|
||||
hasPotentiallyPollutingDecl = true;
|
||||
setWarning(WarningKind.UNSAFE_DECL);
|
||||
} else if (diagnostic.getKind() == Diagnostic.Kind.ERROR &&
|
||||
diagnostic.getCode().contains("invalid.trustme")) {
|
||||
hasMalformedAnnoInDecl = true;
|
||||
setWarning(WarningKind.MALFORMED_SAFEVARARGS);
|
||||
}
|
||||
}
|
||||
|
||||
void setWarning(WarningKind wk) {
|
||||
if (!warnings.add(wk)) {
|
||||
throw new AssertionError("Duplicate warning of kind " + wk + " in source:\n" + source);
|
||||
}
|
||||
}
|
||||
|
||||
boolean hasWarning(WarningKind wk) {
|
||||
return warnings.contains(wk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user