summaryrefslogtreecommitdiff
path: root/core/java12/com/vladium/jcd/lib/Types.java
blob: 05b423033f5107da9cb612244b88dc98d266d106 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
/* Copyright (C) 2003 Vladimir Roubtsov. All rights reserved.
 * 
 * This program and the accompanying materials are made available under
 * the terms of the Common Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/cpl-v10.html
 * 
 * $Id: Types.java,v 1.1.1.1 2004/05/09 16:57:50 vlad_r Exp $
 */
package com.vladium.jcd.lib;

import java.io.IOException;
import java.lang.reflect.*;

import com.vladium.jcd.cls.IAccessFlags;

// ----------------------------------------------------------------------------
/**
 * Utility methods for manipulating type signatures and descriptors.
 * 
 * TODO: fix usage of chars in parsers
 * 
 * @author (C) 2001, Vlad Roubtsov
 */
public abstract class Types
{
    // public: ................................................................
    
    /**
     * Returns 'c''s package name [does not include trailing '.'] or ""
     * if 'c' is in the default package.
     */
    public static String getClassPackageName (final Class c)
    {
        // TODO: handle array and other types
        
        final String className = c.getName ();
        final int lastDot = className.lastIndexOf ('.');
        return lastDot >= 0 ? className.substring (0, lastDot) : "";
    }
    
    
    public static String accessFlagsToString (final int flags, final boolean isClass)
    {
        final StringBuffer result = new StringBuffer ();
      
        boolean first = true;
        
        if (isClass)
        {
            for (int f = 0; f < IAccessFlags.ALL_ACC.length; ++ f)
            {
                final int bit = IAccessFlags.ALL_ACC [f];
                
                if ((flags & bit) != 0)
                {
                    if (first)
                        first = false;
                    else
                        result.append (" ");
                    
                    if (bit == IAccessFlags.ACC_SUPER)
                        result.append ("super");
                    else
                        result.append (IAccessFlags.ALL_ACC_NAMES [f]);
                }
            }
        }
        else
        {
            for (int f = 0; f < IAccessFlags.ALL_ACC.length; ++ f)
            {
                final int bit = IAccessFlags.ALL_ACC [f];
                
                if ((flags & bit) != 0)
                {
                    if (first)
                        first = false;
                    else
                        result.append (" ");
                        
                    result.append (IAccessFlags.ALL_ACC_NAMES [f]);
                }
            }
        }
        
        return result.toString ();
    } 

    
    /**
     * Converts Java-styled package/class name to how it would be
     * represented in the VM.<P>
     * 
     * Example:<BR>
     * javaNameToVMName("java.lang.Object") = "java/lang/Object"
     * 
     * @see #vmNameToJavaName
     */
    public static String javaNameToVMName (final String javaName)
    {
        if (javaName == null) return null;
        return javaName.replace ('.', '/');
    }
    
    
    /**
     * Converts a VM-styled package/class name to how it would be
     * represented in Java.<P>
     * 
     * Example:<BR>
     * vmNameToJavaName("java/lang/Object") = "java.lang.Object"
     * 
     * @see #javaNameToVMName
     */
    public static String vmNameToJavaName (final String vmName)
    {
        if (vmName == null) return null;
        return vmName.replace ('/', '.');
    }
    
    
    /**
     * Converts a method signature to its VM descriptor representation.
     * See $4.3 of the VM spec 1.0 for the descriptor grammar.<P>
     * 
     * Example:<BR>
     * signatureToDescriptor(new Object().getClass().getMethod("equals" ,new Class[0])) = "(Ljava/lang/Object;)Z"
     * <P>
     * 
     * Equivalent to
     * <CODE>signatureToDescriptor(method.getParameterTypes (), method.getReturnType ())</CODE>.
     */
    public static String signatureToDescriptor (Method method)
    {
        if (method == null) throw new IllegalArgumentException ("null input: method");
        return signatureToDescriptor (method.getParameterTypes (), method.getReturnType ());
    }
    
    
    /**
     * Converts a method signature (parameter types + return type) to its VM descriptor
     * representation. See $4.3 of the VM spec 1.0 for the descriptor grammar.<P>
     */
    public static String signatureToDescriptor (Class [] parameterTypes, Class returnType)
    {
        return new signatureCompiler ().signatureDescriptor (parameterTypes, returnType);
    }
    
    
    /**
     * Converts a type (a Class) to its VM descriptor representation.<P>
     * 
     * Example:<BR>
     * typeToDescriptor(Object.class) = "Ljava/lang/Object;" <BR>
     * typeToDescriptor(boolean.class) = "Z"
     * <P>
     * Note the invariant typeToDescriptor(descriptorToType(desc)) == desc.
     * 
     * @see #descriptorToType
     */
    public static String typeToDescriptor (Class type)
    {
        return new signatureCompiler ().typeDescriptor (type);
    }
    
    
    /**
     * Converts a VM descriptor to the corresponding type.<P>
     * 
     * Example:<BR>
     * descriptorToType("[[I") = int[][].class <BR>
     * descriptorToType("B") = byte.class
     * <P>
     * Note the invariant descriptorToType(typeToDescriptor(c)) == c.
     * 
     * @see #descriptorToType
     */
    public static Class descriptorToType (String typedescriptor) throws ClassNotFoundException
    {
        return new typeDescriptorCompiler ().descriptorToClass (typedescriptor);
    }
    
    
    
    public static String descriptorToReturnType (String methoddescriptor)
    {
        final int i1 = methoddescriptor.indexOf ('(');
        final int i2 = methoddescriptor.lastIndexOf (')');
        
        if ((i1 < 0) || (i2 <= 0) || (i1 >= i2) || (i2 >= methoddescriptor.length () - 1))
            throw new IllegalArgumentException ("malformed method descriptor: [" + methoddescriptor + "]");

        return methoddescriptor.substring (i2 + 1);                                                                                                
    }
    
    
    public static String [] descriptorToParameterTypes (String methoddescriptor)
    {
        //System.out.println ("METHOD DESCRIPTOR: [" + methoddescriptor + "]");
    
        try
        {
            final methodDescriptorCompiler compiler = new methodDescriptorCompiler (methoddescriptor);
            compiler.methodDescriptor ();
            return compiler.getResult ();
        }
        catch (IOException e)
        {
            throw new IllegalArgumentException ("error parsing [" + methoddescriptor + "]: " + e.toString ());
        }
        
        /*
        final java.util.Vector _result = new java.util.Vector ();
        final StringBuffer token = new StringBuffer ();

        char c = '*';
        int scan = 0;
        
        for (int state = 0; state != 4; )
        {
            try
            {
                switch (state)
                {
                case 0:
                    c = methoddescriptor.charAt (scan++);
                    if (c == '(')
                        state = 1;
                    else
                        throw new IllegalArgumentException ("malformed method descriptor: [" + methoddescriptor + "]");
                    break;
                    
                case 1:
                    c = methoddescriptor.charAt (scan);
                    switch (c)
                    {
                    case 'B':
                    case 'C':
                    case 'D':
                    case 'F':
                    case 'I':
                    case 'J':
                    case 'S':
                    case 'Z':
                        token.append (c);
                        _result.addElement (token.toString ());
                        token.setLength (0);
                        scan++;
                        break;
                        
                    case 'L':
                        state = 2;
                        token.append (c);
                        scan++;
                        break;
                        
                    case '[':
                        state = 3;    
                        token.append (c);
                        scan++;
                        break;
                        
                    case ')':
                        if (token.length () > 0)
                        {
                            _result.addElement (token.toString ());
                            token.setLength (0);
                        }
                        state = 4;
                        break;
                            
                        
                    default:
                        throw new IllegalArgumentException ("[state = " + state + ", c = " + c + "] malformed method descriptor: [" + methoddescriptor + "]");
                        
                    } // end of nested switch
                    break;
                    
                case 2:
                    c = methoddescriptor.charAt (scan++);
                    token.append (c);
                    if (c == ';')
                    {
                        _result.addElement (token.toString ());
                        token.setLength (0);
                        state = 1;
                    }
                    break;
                    
                case 3:
                    c = methoddescriptor.charAt (scan++);
                    token.append (c);
                    if (c != '[')
                    {
                        state = 1;
                    }
                    break;    
                    
                } // end of switch
                
                //System.out.println ("[state = " + state + ", c = " + c + "]");
            }
            catch (StringIndexOutOfBoundsException e)
            {
                throw new IllegalArgumentException ("malformed method descriptor: [" + methoddescriptor + "]");
            }
        }
        
        String [] result = new String [_result.size ()];
        _result.copyInto (result);
        
        return result;
        */
    }
    
    
    public static String signatureToMethodDescriptor (final String [] parameterTypeDescriptors, final String returnTypeDescriptor)
    {
        final StringBuffer result = new StringBuffer ("(");
        
        for (int p = 0; p < parameterTypeDescriptors.length; p++)
        {
            result.append (parameterTypeDescriptors [p]);
        }
        
        result.append (')');
        result.append (returnTypeDescriptor);
        
        return result.toString (); 
    }
    
    
    public static String typeDescriptorToUserName (final String typedescriptor)
    {
        return new typeDescriptorCompiler2 ().descriptorToClass (typedescriptor);
    }
    
    public static String methodDescriptorToUserName (final String methoddescriptor)
    {
        final String [] parameterTypes = descriptorToParameterTypes (methoddescriptor);
        
        final StringBuffer result = new StringBuffer ("(");
        
        for (int p = 0; p < parameterTypes.length; p++)
        {
            //System.out.println ("DESCRIPTOR: [" + parameterTypes [p] + "]");
            
            if (p > 0) result.append (", ");
            
            final String typeUserName = typeDescriptorToUserName (parameterTypes [p]);
            int lastDot = typeUserName.lastIndexOf ('.');
            
            if ((lastDot < 0) || ! "java.lang.".equals (typeUserName.substring (0, lastDot + 1)))
                result.append (typeUserName);
            else
                result.append (typeUserName.substring (lastDot + 1));
        }
        
        result.append (')');
        return result.toString (); 
    }
    
    public static String fullMethodDescriptorToUserName (final String classJavaName, String methodName, final String methoddescriptor)
    {
        if ("<init>".equals (methodName))
            methodName = simpleClassName (classJavaName);
        if ("<clinit>".equals (methodName))
            methodName = "<static class initializer>";
        
        return methodName + ' ' + methodDescriptorToUserName (methoddescriptor);
    }
    
    // TODO: added most recently
    public static String fullMethodDescriptorToFullUserName (final String classJavaName, String methodName, final String methoddescriptor)
    {
        if ("<init>".equals (methodName))
            methodName = simpleClassName (classJavaName);
        if ("<clinit>".equals (methodName))
            methodName = "<static class initializer>";
        
        return classJavaName + '.' + methodName + ' ' + methodDescriptorToUserName (methoddescriptor);
    }
    
    // protected: .............................................................
    
    // package: ...............................................................

    // private: ...............................................................

    
    private static String simpleClassName (final String classJavaName)
    {
        int lastDot = classJavaName.lastIndexOf ('.');
        
        if (lastDot < 0)
            return classJavaName;
        else
            return classJavaName.substring (lastDot + 1);
    }
                                     
    
    
    private static final class signatureCompiler
    {
        String signatureDescriptor (Class [] _parameterTypes, Class _returnType)
        {
            emit ('(');    parameterTypes (_parameterTypes); emit (')'); returnType (_returnType);
            
            return m_desc.toString ();
        }
        
        String typeDescriptor (Class type)
        {
            parameterType (type);
            
            return m_desc.toString ();
        }
        
        
        private void parameterTypes (Class [] _parameterTypes)
        {
            if (_parameterTypes != null)
            {
                for (int p = 0; p < _parameterTypes.length; p++)
                {
                    parameterType (_parameterTypes [p]);
                }
            }
        }
        
        
        private void returnType (Class _returnType)
        {
            if ((_returnType == null) || (_returnType == Void.TYPE))
                emit ('V');
            else
                parameterType (_returnType);
        }
        
        
        private void parameterType (Class _parameterType)
        {
            if (_parameterType != null)
            {
                if (_parameterType.isPrimitive ()) // base type:
                {
                    if (byte.class == _parameterType)            emit ('B');
                    else if (char.class == _parameterType)        emit ('C');
                    else if (double.class == _parameterType)    emit ('D');
                    else if (float.class == _parameterType)        emit ('F');
                    else if (int.class == _parameterType)        emit ('I');
                    else if (long.class == _parameterType)        emit ('J');
                    else if (short.class == _parameterType)        emit ('S');
                    else if (boolean.class == _parameterType)    emit ('Z');
                }
                else if (_parameterType.isArray ()) // array type:
                {
                    emit ('[');    parameterType (_parameterType.getComponentType ());
                }
                else // object type:
                {
                    emit ('L');    emit (javaNameToVMName (_parameterType.getName ())); emit (';');
                }
            }
        }
        
        
        private void emit (String s)
        {
            m_desc.append (s);
        }
        
        private void emit (char c)
        {
            m_desc.append (c);
        }
        
        
        private StringBuffer m_desc = new StringBuffer ();
        
    } // end of static class
    
    
    
    private static class typeDescriptorCompiler
    {
        /*
        NOTE: the following would be a very simple solution to this problem
        
            Class.forName ('[' + descriptor).getComponentType ();
        
        except it only works in MS VM.
        */
        
        Class descriptorToClass (String typedescriptor) throws ClassNotFoundException
        {
            char first = typedescriptor.charAt (0);
            
            if (first == '[')
                // array type:
                return arrayOf (typedescriptor.substring (1));
            else if (first == 'L')
                // object type:
                return Class.forName (vmNameToJavaName (typedescriptor.substring (1, typedescriptor.length() - 1)));
            else // primitive type
            {
                return primitive (first);
            }
        }
        
        
        Class arrayOf (String typedescriptor) throws ClassNotFoundException
        {
            char first = typedescriptor.charAt (0);
            Class component;
            
            if (first == '[')
                // array type:
                component = arrayOf (typedescriptor.substring (1));
            else if (first == 'L')
                // object type:
                component =  Class.forName (vmNameToJavaName (typedescriptor.substring (1, typedescriptor.length() - 1)));
            else // primitive type
            {
                component = primitive (first);
            }
            
            Object array = Array.newInstance (component, 0);
            return array.getClass ();
        }
        
        
        Class primitive (char c) throws ClassNotFoundException
        {
            if (c == 'B') return byte.class;
            else if (c == 'C') return char.class;
            else if (c == 'D') return double.class;
            else if (c == 'F') return float.class;
            else if (c == 'I') return int.class;
            else if (c == 'J') return long.class;
            else if (c == 'S') return short.class;
            else if (c == 'Z') return boolean.class;
            else throw new ClassNotFoundException ("unknown base type: " + c);
        }
        
    } // end of static class

    
    private static class typeDescriptorCompiler2
    {
        String descriptorToClass (String typedescriptor)
        {
            //System.out.println ("typedesc1 -> " + typedescriptor);
            
            char first = typedescriptor.charAt (0);
            
            if (first == '[')
                // array type:
                return arrayOf (typedescriptor.substring (1));
            else if (first == 'L')
                // object type:
                return vmNameToJavaName (typedescriptor.substring (1, typedescriptor.length() - 1));
            else // primitive type
                return primitive (first);
        }
        
        
        String arrayOf (String typedescriptor)
        {
            //System.out.println ("typedesc2 -> " + typedescriptor);
            
            char first = typedescriptor.charAt (0);
            String component;
            
            if (first == '[')
                // array type:
                component = arrayOf (typedescriptor.substring (1));
            else if (first == 'L')
                // object type:
                component = vmNameToJavaName (typedescriptor.substring (1, typedescriptor.length() - 1));
            else // primitive type
                component = primitive (first);
            
            String array = component + " []";
            return array;
        }
        
        
        String primitive (char c)
        {
            switch (c)
            {
            case 'B': return "byte";
            case 'C': return "char";
            case 'D': return "double";
            case 'F': return "float";
            case 'I': return "int";
            case 'J': return "long";
            case 'S': return "short";
            case 'Z': return "boolean";
            default:          
                throw new IllegalArgumentException ("unknown primitive: " + c);
            }
        }
        
    } // end of static class

    
    private static class methodDescriptorCompiler
    {
        methodDescriptorCompiler (String methoddescriptor)
        {
            m_in = new java.io.PushbackReader (new java.io.StringReader (methoddescriptor));
        }
        
        String [] getResult ()
        {
            final String [] result = new String [m_result.size ()];
            m_result.toArray (result);
            
            return result;
        }
        
        void methodDescriptor () throws IOException
        {
            consume ('(');
            
            char c;
            while ((c = (char) m_in.read ()) != ')')
            {
                m_in.unread (c);
                parameterDescriptor ();
            }
            returnDescriptor ();
        }
        
        void parameterDescriptor () throws IOException
        {
            fieldType ();
            newToken ();
        }
        
        void returnDescriptor () throws IOException
        {
            char c = (char) m_in.read ();
            
            switch (c)
            {
            case 'V':
                m_token.append (c);
                break;
                
            default:
                m_in.unread (c);
                fieldType ();
                
            }
            // ignore return type for now: newToken ();
        }
        
        void componentType () throws IOException
        {
            fieldType ();
        }
        
        void objectType () throws IOException
        {
            consume ('L');
            m_token.append ('L');
            
            char c;
            while ((c = (char) m_in.read ()) != ';')
            {
                m_token.append (c);
            }
            m_token.append (';');
        }
        
        void arrayType () throws IOException
        {
            consume ('[');
            m_token.append ('[');
        
            componentType ();
        }
        
        void fieldType () throws IOException
        {
            char c = (char) m_in.read ();
            m_in.unread (c);
            
            switch (c)
            {
            case 'L':
                objectType ();
                break;
                
            case '[':
                arrayType ();
                break;
                
            default:
                baseType ();
                break;
            }
        }

        
        void baseType () throws IOException
        {
            char c = (char) m_in.read ();
            
            switch (c)
            {
            case 'B': 
            case 'C': 
            case 'D':
            case 'F':
            case 'I':
            case 'J':
            case 'S':
            case 'Z':
                m_token.append (c);
                break;
                
            default:          
                throw new IllegalArgumentException ("unknown base type: " + c);
            }
        }
        
        
        private void consume (char expected) throws IOException
        {
            char c = (char) m_in.read ();
            
            if (c != expected)
                throw new IllegalArgumentException ("consumed '" + c + "' while expecting '" + expected + "'");
        }
        
        
        
        private void newToken ()
        {
            //System.out.println ("NEW TOKEN [" + m_token.toString () + "]");
            
            m_result.add (m_token.toString ());
            m_token.setLength (0);
        }
    
        final java.util.List m_result = new java.util.ArrayList ();
        private StringBuffer m_token = new StringBuffer ();
        private java.io.PushbackReader m_in;
    } // end of nested class
    
} // end of class
// ----------------------------------------------------------------------------