summaryrefslogtreecommitdiff
path: root/xml/dom-impl/src/com/intellij/util/xml/impl/DomInvocationHandler.java
blob: a0529b60a8fcce33e036d7fc354f8a46dfc8a8a2 (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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.util.xml.impl;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.NullableFactory;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiInvalidElementAccessException;
import com.intellij.psi.SmartPointerManager;
import com.intellij.psi.SmartPsiElementPointer;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.semantic.SemElement;
import com.intellij.semantic.SemKey;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xml.*;
import com.intellij.util.xml.events.DomEvent;
import com.intellij.util.xml.reflect.*;
import com.intellij.util.xml.stubs.AttributeStub;
import com.intellij.util.xml.stubs.DomStub;
import com.intellij.util.xml.stubs.ElementStub;
import com.intellij.util.xml.stubs.StubParentStrategy;
import net.sf.cglib.proxy.AdvancedProxy;
import net.sf.cglib.proxy.InvocationHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author peter
 */
public abstract class DomInvocationHandler<T extends AbstractDomChildDescriptionImpl, Stub extends DomStub> extends UserDataHolderBase implements InvocationHandler, DomElement,
                                                                                                                            SemElement {
  private static final Logger LOG = Logger.getInstance("#com.intellij.util.xml.impl.DomInvocationHandler");
  public static final Method ACCEPT_METHOD = ReflectionUtil.getMethod(DomElement.class, "accept", DomElementVisitor.class);
  public static final Method ACCEPT_CHILDREN_METHOD = ReflectionUtil.getMethod(DomElement.class, "acceptChildren", DomElementVisitor.class);
  private static final JavaMethod ourGetValue = JavaMethod.getMethod(GenericValue.class, new JavaMethodSignature("getValue"));

  private final Type myType;
  private final DomManagerImpl myManager;
  private final EvaluatedXmlName myTagName;
  private final T myChildDescription;
  private DomParentStrategy myParentStrategy;
  private volatile long myLastModCount;

  private volatile DomElement myProxy;
  private DomGenericInfoEx myGenericInfo;
  private final InvocationCache myInvocationCache;
  private volatile Converter myScalarConverter = null;
  private volatile SmartFMap<Method, Invocation> myAccessorInvocations = SmartFMap.emptyMap();
  @Nullable protected Stub myStub;

  protected DomInvocationHandler(Type type, DomParentStrategy parentStrategy,
                                 @NotNull final EvaluatedXmlName tagName,
                                 final T childDescription,
                                 final DomManagerImpl manager,
                                 boolean dynamic,
                                 @Nullable Stub stub) {
    myManager = manager;
    myParentStrategy = parentStrategy;
    myTagName = tagName;
    myChildDescription = childDescription;
    myStub = stub;
    myLastModCount = manager.getPsiModificationCount();

    myType = narrowType(type);

    myInvocationCache = manager.getApplicationComponent().getInvocationCache(getRawType());
    refreshGenericInfo(dynamic);
    if (stub != null) {
      stub.setHandler(this);
    }
  }

  protected Type narrowType(@NotNull Type nominalType) {
    return nominalType;
  }

  @Override
  @Nullable
  public DomElement getParent() {
    final DomInvocationHandler handler = getParentHandler();
    return handler == null ? null : handler.getProxy();
  }

  protected final void assertValid() {
    final String s = checkValidity();
    if (s != null) {
      throw new AssertionError(myType.toString() + " @" + hashCode() + "\nclass=" + getClass() + "\nxml=" + getXmlElement() + "; " + s);
    }
  }

  @Nullable
  final DomInvocationHandler getParentHandler() {
    return getParentStrategy().getParentHandler();
  }

  @Nullable
  public Stub getStub() {
    return myStub;
  }

  @Override
  @NotNull
  public final Type getDomElementType() {
    return myType;
  }

  @Nullable
  protected String getValue() {
    final XmlTag tag = getXmlTag();
    return tag == null ? null : getTagValue(tag);
  }

  protected void setValue(@Nullable final String value) {
    final XmlTag tag = ensureTagExists();
    myManager.runChange(new Runnable() {
      @Override
      public void run() {
        setTagValue(tag, value);
      }
    });
    myManager.fireEvent(new DomEvent(getProxy(), false));
  }

  @Override
  public void copyFrom(final DomElement other) {
    if (other == getProxy()) return;
    assert other.getDomElementType().equals(myType) : "Can't copy from " + other.getDomElementType() + " to " + myType;

    if (other.getXmlElement() == null) {
      undefine();
      return;
    }

    myManager.performAtomicChange(new Runnable() {
      @Override
      public void run() {
        ensureXmlElementExists();
        final DomInvocationHandler otherInvocationHandler = DomManagerImpl.getDomInvocationHandler(other);
        assert otherInvocationHandler != null : other;

        final DomGenericInfoEx genericInfo = otherInvocationHandler.getGenericInfo();
        for (final AttributeChildDescriptionImpl description : genericInfo.getAttributeChildrenDescriptions()) {
          description.getDomAttributeValue(DomInvocationHandler.this).setStringValue(description.getDomAttributeValue(other).getStringValue());
        }
        for (final DomFixedChildDescription description : genericInfo.getFixedChildrenDescriptions()) {
          final List<? extends DomElement> list = description.getValues(getProxy());
          final List<? extends DomElement> otherValues = description.getValues(other);
          for (int i = 0; i < list.size(); i++) {
            final DomElement otherValue = otherValues.get(i);
            final DomElement value = list.get(i);
            if (!DomUtil.hasXml(otherValue)) {
              value.undefine();
            }
            else {
              value.copyFrom(otherValue);
            }
          }
        }
        for (final DomCollectionChildDescription description : genericInfo.getCollectionChildrenDescriptions()) {
          for (final DomElement value : description.getValues(getProxy())) {
            value.undefine();
          }
          for (final DomElement otherValue : description.getValues(other)) {
            description.addValue(getProxy(), otherValue.getDomElementType()).copyFrom(otherValue);
          }
        }

        final String stringValue = otherInvocationHandler.getValue();
        if (StringUtil.isNotEmpty(stringValue)) {
          setValue(stringValue);
        }
      }
    });

    if (!myManager.getSemService().isInsideAtomicChange()) {
      myManager.fireEvent(new DomEvent(getProxy(), false));
    }
  }

  @Override
  public <T extends DomElement> T createStableCopy() {
    XmlTag tag = getXmlTag();
    if (tag != null && tag.isPhysical()) {
      final DomElement existing = myManager.getDomElement(tag);
      assert existing != null : existing + "\n---------\n" + tag.getParent().getText() + "\n-----------\n" + tag.getText();
      assert getProxy().equals(existing) : existing + "\n---------\n" + tag.getParent().getText() + "\n-----------\n" + tag.getText() + "\n----\n" + this + " != " +
                                           DomManagerImpl.getDomInvocationHandler(existing);
      final SmartPsiElementPointer<XmlTag> pointer =
        SmartPointerManager.getInstance(myManager.getProject()).createSmartPsiElementPointer(tag);
      return myManager.createStableValue(new StableCopyFactory<T>(pointer, myType, getClass()));
    }
    return (T)createPathStableCopy();
  }

  protected DomElement createPathStableCopy() {
    throw new UnsupportedOperationException();
  }

  @Override
  public final <T extends DomElement> T createMockCopy(final boolean physical) {
    final T copy = myManager.createMockElement((Class<? extends T>)getRawType(), getProxy().getModule(), physical);
    copy.copyFrom(getProxy());
    return copy;
  }

  @Override
  @NotNull
  public String getXmlElementNamespace() {
    final DomInvocationHandler parent = getParentHandler();
    assert parent != null : "this operation should be performed on the DOM having a physical parent, your DOM may be not very fresh";
    final XmlElement element = parent.getXmlElement();
    assert element != null;
    return getXmlName().getNamespace(element, getFile());
  }

  @Override
  @Nullable
  public String getXmlElementNamespaceKey() {
    return getXmlName().getXmlName().getNamespaceKey();
  }

  @Override
  public final Module getModule() {
    final Module module = ModuleUtilCore.findModuleForPsiElement(getFile());
    return module != null ? module : DomUtil.getFile(this).getUserData(DomManager.MOCK_ELEMENT_MODULE);
  }

  @Override
  public XmlTag ensureTagExists() {
    assertValid();

    XmlTag tag = getXmlTag();
    if (tag != null) return tag;

    tag = setEmptyXmlTag();
    setXmlElement(tag);

    final DomElement element = getProxy();
    myManager.fireEvent(new DomEvent(element, true));
    addRequiredChildren();
    myManager.cacheHandler(getCacheKey(), tag, this);
    return getXmlTag();
  }

  @Override
  public XmlElement getXmlElement() {
    return getParentStrategy().getXmlElement();
  }

  @Override
  public boolean exists() {
    return getParentStrategy().isPhysical();
  }

  private DomParentStrategy getParentStrategy() {
    myParentStrategy = myParentStrategy.refreshStrategy(this);
    return myParentStrategy;
  }

  @Override
  public XmlElement ensureXmlElementExists() {
    return ensureTagExists();
  }

  protected final XmlTag createChildTag(final EvaluatedXmlName tagName) {
    final String localName = tagName.getXmlName().getLocalName();
    if (localName.contains(":")) {
      try {
        return XmlElementFactory.getInstance(myManager.getProject()).createTagFromText("<" + localName + "/>");
      }
      catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }

    final XmlElement element = getXmlElement();
    assert element != null;
    return getXmlTag().createChildTag(localName, tagName.getNamespace(element, getFile()), null, false);
  }

  @Override
  public final boolean isValid() {
    return checkValidity() == null;
  }

  String toStringEx() {
    return myType.toString() + " @" + hashCode() + "&handler=" + super.toString() + "&cd=" + myChildDescription + "&ps=" + myParentStrategy;
  }

  @Nullable
  protected String checkValidity() {
    ProgressManager.checkCanceled();
    final DomParentStrategy parentStrategy = getParentStrategy();
    String error = parentStrategy.checkValidity();
    if (error != null) {
      return "Strategy: " + error;
    }

    final long modCount = myManager.getPsiModificationCount();
    if (myLastModCount == modCount) {
      return null;
    }

    final XmlElement xmlElement = parentStrategy.getXmlElement();
    if (xmlElement != null) {
      final DomInvocationHandler actual = myManager.getDomHandler(xmlElement);
      if (!equals(actual)) {
        return "element changed: " + this.toStringEx() + "!=" + (actual == null ? null : actual.toStringEx());
      }
      myLastModCount = modCount;
      return null;
    }

    final DomInvocationHandler parent = getParentHandler();
    if (parent == null) {
      return "no parent: " + getDomElementType();
    }

    error = parent.checkValidity();
    if (error != null) {
      return "parent: " + error;
    }

    myLastModCount = modCount;
    return null;
  }


  @Override
  @NotNull
  public final DomGenericInfoEx getGenericInfo() {
    return myGenericInfo;
  }

  protected abstract void undefineInternal();

  @Override
  public final void undefine() {
    undefineInternal();
  }

  protected final void deleteTag(final XmlTag tag) {
    final boolean changing = myManager.setChanging(true);
    try {
      tag.delete();
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    finally {
      myManager.setChanging(changing);
    }
  }

  protected final void fireUndefinedEvent() {
    myManager.fireEvent(new DomEvent(getProxy(), false));
  }

  protected abstract XmlTag setEmptyXmlTag();

  protected void addRequiredChildren() {
    for (final AbstractDomChildrenDescription description : getGenericInfo().getChildrenDescriptions()) {
      if (description instanceof DomAttributeChildDescription) {
        final Required required = description.getAnnotation(Required.class);

        if (required != null && required.value()) {
          description.getValues(getProxy()).get(0).ensureXmlElementExists();
        }
      }
      else if (description instanceof DomFixedChildDescription) {
        final DomFixedChildDescription childDescription = (DomFixedChildDescription)description;
        List<? extends DomElement> values = null;
        final int count = childDescription.getCount();
        for (int i = 0; i < count; i++) {
          final Required required = childDescription.getAnnotation(i, Required.class);
          if (required != null && required.value()) {
            if (values == null) {
              values = description.getValues(getProxy());
            }
            values.get(i).ensureTagExists();
          }
        }
      }
    }
  }

  @Override
  @NotNull
  public final String getXmlElementName() {
    return myTagName.getXmlName().getLocalName();
  }

  @NotNull
  public final EvaluatedXmlName getXmlName() {
    return myTagName;
  }

  @Override
  public void accept(final DomElementVisitor visitor) {
    ProgressManager.checkCanceled();
    myManager.getApplicationComponent().getVisitorDescription(visitor.getClass()).acceptElement(visitor, getProxy());
  }

  @Override
  @SuppressWarnings("ForLoopReplaceableByForEach")
  public void acceptChildren(DomElementVisitor visitor) {
    ProgressManager.checkCanceled();
    final DomElement element = getProxy();
    List<? extends AbstractDomChildrenDescription> descriptions = getGenericInfo().getChildrenDescriptions();
    for (int i = 0, descriptionsSize = descriptions.size(); i < descriptionsSize; i++) {
      AbstractDomChildrenDescription description = descriptions.get(i);
      List<? extends DomElement> values = description.getValues(element);
      for (int j = 0, valuesSize = values.size(); j < valuesSize; j++) {
        DomElement value = values.get(j);
        value.accept(visitor);
      }
    }
  }

  @NotNull
  protected final Converter getScalarConverter() {
    Converter converter = myScalarConverter;
    if (converter == null) {
      converter = myScalarConverter = createConverter(ourGetValue);
    }
    return converter;
  }

  @NotNull
  private Converter createConverter(final JavaMethod method) {
    final Type returnType = method.getGenericReturnType();
    final Type type = returnType == void.class ? method.getGenericParameterTypes()[0] : returnType;
    final Class parameter = DomUtil.substituteGenericType(type, myType);
    if (parameter == null) {
      LOG.error(type + " " + myType);
    }
    Converter converter = getConverter(new AnnotatedElement() {
      @Override
      public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
        return myInvocationCache.getMethodAnnotation(method, annotationClass);
      }
    }, parameter);
    if (converter == null && type instanceof TypeVariable) {
      converter = getConverter(this, DomUtil.getGenericValueParameter(myType));
    }
    if (converter == null) {
      converter =  myManager.getConverterManager().getConverterByClass(parameter);
    }
    if (converter == null) {
      throw new AssertionError("No converter specified: String<->" + parameter.getName() + "; method=" + method + "; place=" + myChildDescription);
    }
    return converter;
  }

  @Override
  public final T getChildDescription() {
    return myChildDescription;
  }

  @Override
  @Nullable
  public <T extends Annotation> T getAnnotation(final Class<T> annotationClass) {
    final AnnotatedElement childDescription = getChildDescription();
    if (childDescription != null) {
      final T annotation = childDescription.getAnnotation(annotationClass);
      if (annotation != null) return annotation;
    }

    return getClassAnnotation(annotationClass);
  }

  protected <T extends Annotation> T getClassAnnotation(Class<T> annotationClass) {
    return myInvocationCache.getClassAnnotation(annotationClass);
  }

  @Nullable
  private Converter getConverter(final AnnotatedElement annotationProvider,
                                 Class parameter) {
    final Resolve resolveAnnotation = annotationProvider.getAnnotation(Resolve.class);
    if (resolveAnnotation != null) {
      final Class<? extends DomElement> aClass = resolveAnnotation.value();
      if (!DomElement.class.equals(aClass)) {
        return DomResolveConverter.createConverter(aClass);
      } else {
        LOG.assertTrue(parameter != null, "You should specify @Resolve#value() parameter");
        return DomResolveConverter.createConverter(parameter);
      }
    }

    final ConverterManager converterManager = myManager.getConverterManager();
    Convert convertAnnotation = annotationProvider.getAnnotation(Convert.class);
    if (convertAnnotation != null) {
      if (convertAnnotation instanceof ConvertAnnotationImpl) {
        return ((ConvertAnnotationImpl)convertAnnotation).getConverter();
      }
      return converterManager.getConverterInstance(convertAnnotation.value());
    }

    return null;
  }

  @NotNull
  public final DomElement getProxy() {
    DomElement proxy = myProxy;
    if (proxy == null) {
      Class<?> rawType = getRawType();
      Class<? extends DomElement> implementation = myManager.getApplicationComponent().getImplementation(rawType);
      final boolean isInterface = rawType.isInterface();
      if (implementation == null && !isInterface) {
        //noinspection unchecked
        implementation = (Class<? extends DomElement>)rawType;
      }
      myProxy = proxy = AdvancedProxy.createProxy(this, implementation, isInterface ? new Class[]{rawType} : ArrayUtil.EMPTY_CLASS_ARRAY);
    }
    return proxy;
  }

  @NotNull
  public final XmlFile getFile() {
    return getParentStrategy().getContainingFile(this);
  }

  @Override
  @NotNull
  public DomNameStrategy getNameStrategy() {
    final Class<?> rawType = getRawType();
    final DomNameStrategy strategy = DomImplUtil.getDomNameStrategy(rawType, isAttribute());
    if (strategy != null) {
      return strategy;
    }
    final DomInvocationHandler handler = getParentHandler();
    return handler == null ? DomNameStrategy.HYPHEN_STRATEGY : handler.getNameStrategy();
  }

  protected boolean isAttribute() {
    return false;
  }

  @Override
  @NotNull
  public ElementPresentation getPresentation() {
    ElementPresentationTemplate template = getChildDescription().getPresentationTemplate();
    if (template != null) {
      return template.createPresentation(getProxy());
    }
    return new ElementPresentation() {
      @Override
      public String getElementName() {
        return ElementPresentationManager.getElementName(getProxy());
      }

      @Override
      public String getTypeName() {
        return ElementPresentationManager.getTypeNameForObject(getProxy());
      }

      @Override
      public Icon getIcon() {
        return ElementPresentationManager.getIconOld(getProxy());
      }
    };
  }

  @Override
  public final GlobalSearchScope getResolveScope() {
    return DomUtil.getFile(this).getResolveScope();
  }

  private static <T extends DomElement> T _getParentOfType(Class<T> requiredClass, DomElement element) {
    while (element != null && !requiredClass.isInstance(element)) {
      element = element.getParent();
    }
    return (T)element;
  }

  @Override
  public final <T extends DomElement> T getParentOfType(Class<T> requiredClass, boolean strict) {
    return _getParentOfType(requiredClass, strict ? getParent() : getProxy());
  }

  @NotNull
  final IndexedElementInvocationHandler getFixedChild(final Pair<FixedChildDescriptionImpl, Integer> info) {
    final FixedChildDescriptionImpl description = info.first;
    XmlName xmlName = description.getXmlName();
    final EvaluatedXmlName evaluatedXmlName = createEvaluatedXmlName(xmlName);
    if (myStub != null && description.isStubbed()) {
      List<DomStub> stubs = myStub.getChildrenByName(xmlName.getLocalName(), xmlName.getNamespaceKey());
      DomStub stub = stubs.isEmpty() ? null : stubs.get(0);
      DomParentStrategy strategy = stub == null ? new StubParentStrategy.Empty(myStub) : new StubParentStrategy(stub);
      return new IndexedElementInvocationHandler(evaluatedXmlName, description, 0, strategy, myManager, (ElementStub)stub);
    }
    final XmlTag tag = getXmlTag();
    final int index = info.second;
    if (tag != null) {
      if (!tag.isValid()) {
        throw new PsiInvalidElementAccessException(tag);
      }
      final XmlTag[] subTags = tag.getSubTags();
      for (int i = 0, subTagsLength = subTags.length; i < subTagsLength; i++) {
        XmlTag xmlTag = subTags[i];
        if (!xmlTag.isValid()) {
          throw new PsiInvalidElementAccessException(xmlTag,
                                                     "invalid children of valid tag: " + tag.getText() + "; subtag=" + xmlTag + "; index=" + i);
        }
      }
      final List<XmlTag> tags = DomImplUtil.findSubTags(subTags, evaluatedXmlName, getFile());
      if (tags.size() > index) {
        final XmlTag child = tags.get(index);
        final IndexedElementInvocationHandler semElement = myManager.getSemService().getSemElement(DomManagerImpl.DOM_INDEXED_HANDLER_KEY, child);
        if (semElement == null) {
          final IndexedElementInvocationHandler take2 = myManager.getSemService().getSemElement(DomManagerImpl.DOM_INDEXED_HANDLER_KEY, child);
          throw new AssertionError("No DOM at XML. Parent=" + tag + "; child=" + child + "; index=" + index+ "; second attempt=" + take2);

        }
        return semElement;
      }
    }
    return new IndexedElementInvocationHandler(evaluatedXmlName, description, index, new VirtualDomParentStrategy(this), myManager, null);
  }

  @NotNull
  final AttributeChildInvocationHandler getAttributeChild(final AttributeChildDescriptionImpl description) {
    final EvaluatedXmlName evaluatedXmlName = createEvaluatedXmlName(description.getXmlName());
    if (myStub != null && description.isStubbed()) {
      AttributeStub stub = myStub.getAttributeStub(description.getXmlName());
      StubParentStrategy strategy = StubParentStrategy.createAttributeStrategy(stub, myStub);
      return new AttributeChildInvocationHandler(evaluatedXmlName, description, myManager, strategy, stub);
    }
    final XmlTag tag = getXmlTag();

    if (tag != null) {
      // TODO: this seems ugly
      String ns = evaluatedXmlName.getNamespace(tag, getFile());
      final XmlAttribute attribute = tag.getAttribute(description.getXmlName().getLocalName(), ns.equals(tag.getNamespace())? null:ns);

      if (attribute != null) {
        PsiUtilCore.ensureValid(attribute);
        AttributeChildInvocationHandler semElement =
          myManager.getSemService().getSemElement(DomManagerImpl.DOM_ATTRIBUTE_HANDLER_KEY, attribute);
        if (semElement == null) {
          final AttributeChildInvocationHandler take2 = myManager.getSemService().getSemElement(DomManagerImpl.DOM_ATTRIBUTE_HANDLER_KEY, attribute);
          throw new AssertionError("No DOM at XML. Parent=" + tag + "; attribute=" + attribute + "; second attempt=" + take2);
        }
        return semElement;
      }
    }
    return new AttributeChildInvocationHandler(evaluatedXmlName, description, myManager, new VirtualDomParentStrategy(this), null);
  }

  @Override
  @Nullable
  public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      return findInvocation(method).invoke(this, args);
    }
    catch (InvocationTargetException ex) {
      throw ex.getTargetException();
    }
  }

  @NotNull
  private Invocation findInvocation(Method method) {
    Invocation invocation = myAccessorInvocations.get(method);
    if (invocation != null) return invocation;

    invocation = myInvocationCache.getInvocation(method);
    if (invocation != null) return invocation;

    JavaMethod javaMethod = myInvocationCache.getInternedMethod(method);
    invocation = myGenericInfo.createInvocation(javaMethod);
    if (invocation != null) {
      myInvocationCache.putInvocation(method, invocation);
      return invocation;
    }

    if (myInvocationCache.isTagValueGetter(javaMethod)) {
      invocation = new GetInvocation(createConverter(javaMethod));
    }
    else if (myInvocationCache.isTagValueSetter(javaMethod)) {
      invocation = new SetInvocation(createConverter(javaMethod));
    }
    else {
      throw new RuntimeException("No implementation for method " + method.toString() + " in class " + myType);
    }
    myAccessorInvocations = myAccessorInvocations.plus(method, invocation);
    return invocation;
  }

  private static void setTagValue(final XmlTag tag, final String value) {
    tag.getValue().setText(value);
  }

  private static String getTagValue(final XmlTag tag) {
    return tag.getValue().getTrimmedText();
  }

  public final String toString() {
    if (ReflectionUtil.isAssignable(GenericValue.class, getRawType())) {
      return ((GenericValue)getProxy()).getStringValue();
    }
    return myType.toString() + " @" + hashCode();
  }

  public final Class<?> getRawType() {
    return ReflectionUtil.getRawType(myType);
  }

  @Override
  @Nullable
  public XmlTag getXmlTag() {
    return (XmlTag) getXmlElement();
  }

  @Nullable
  protected XmlElement recomputeXmlElement(@NotNull final DomInvocationHandler parentHandler) {
    return null;
  }

  protected final void detach() {
    setXmlElement(null);
  }

  final SemKey getCacheKey() {
    if (this instanceof AttributeChildInvocationHandler) {
      return DomManagerImpl.DOM_ATTRIBUTE_HANDLER_KEY;
    }
    if (this instanceof DomRootInvocationHandler) {
      return DomManagerImpl.DOM_HANDLER_KEY;
    }
    if (this instanceof IndexedElementInvocationHandler) {
      return DomManagerImpl.DOM_INDEXED_HANDLER_KEY;
    }

    if (getChildDescription() instanceof CustomDomChildrenDescription) {
      return DomManagerImpl.DOM_CUSTOM_HANDLER_KEY;
    }

    return DomManagerImpl.DOM_COLLECTION_HANDLER_KEY;
  }

  protected final void setXmlElement(final XmlElement element) {
    refreshGenericInfo(element != null && !isAttribute());
    myStub = null;
    myParentStrategy = element == null ? myParentStrategy.clearXmlElement() : myParentStrategy.setXmlElement(element);
  }

  private void refreshGenericInfo(final boolean dynamic) {
    final StaticGenericInfo staticInfo = myManager.getApplicationComponent().getStaticGenericInfo(myType);
    myGenericInfo = dynamic ? new DynamicGenericInfo(this, staticInfo) : staticInfo;
  }

  @Override
  @NotNull
  public final DomManagerImpl getManager() {
    return myManager;
  }

  public final DomElement addCollectionChild(final CollectionChildDescriptionImpl description, final Type type, int index) throws IncorrectOperationException {
    final EvaluatedXmlName name = createEvaluatedXmlName(description.getXmlName());
    final XmlTag tag = addEmptyTag(name, index);
    final CollectionElementInvocationHandler handler = new CollectionElementInvocationHandler(type, tag, description, this, null);
    myManager.fireEvent(new DomEvent(getProxy(), false));
    getManager().getTypeChooserManager().getTypeChooser(description.getType()).distinguishTag(tag, type);
    handler.addRequiredChildren();
    return handler.getProxy();
  }

  protected final void createFixedChildrenTags(EvaluatedXmlName tagName, FixedChildDescriptionImpl description, int count) {
    final XmlTag tag = ensureTagExists();
    final List<XmlTag> subTags = DomImplUtil.findSubTags(tag, tagName, getFile());
    if (subTags.size() < count) {
      getFixedChild(Pair.create(description, count - 1)).ensureTagExists();
    }
  }

  private XmlTag addEmptyTag(final EvaluatedXmlName tagName, int index) throws IncorrectOperationException {
    final XmlTag tag = ensureTagExists();
    final List<XmlTag> subTags = DomImplUtil.findSubTags(tag, tagName, getFile());
    if (subTags.size() < index) {
      index = subTags.size();
    }
    final boolean changing = myManager.setChanging(true);
    try {
      XmlTag newTag = createChildTag(tagName);
      if (index == 0) {
        if (subTags.isEmpty()) {
          return (XmlTag)tag.add(newTag);
        }

        return (XmlTag)tag.addBefore(newTag, subTags.get(0));
      }

      return (XmlTag)tag.addAfter(newTag, subTags.get(index - 1));
    }
    finally {
      myManager.setChanging(changing);
    }
  }

  @NotNull
  public final EvaluatedXmlName createEvaluatedXmlName(final XmlName xmlName) {
    return getXmlName().evaluateChildName(xmlName);
  }

  public List<? extends DomElement> getCollectionChildren(final AbstractCollectionChildDescription description, final NotNullFunction<DomInvocationHandler, List<XmlTag>> tagsGetter) {
    if (myStub != null && description.isStubbed()) {
      if (description instanceof DomChildDescriptionImpl) {
        XmlName xmlName = ((DomChildDescriptionImpl)description).getXmlName();
        List<DomStub> stubs = myStub.getChildrenByName(xmlName.getLocalName(), xmlName.getNamespaceKey());
        return ContainerUtil.map(stubs, new Function<DomStub, DomElement>() {
          @Override
          public DomElement fun(DomStub stub) {
            return stub.getOrCreateHandler((DomChildDescriptionImpl)description, myManager).getProxy();
          }
        });
      }
      else if (description instanceof CustomDomChildrenDescriptionImpl) {
        List<DomStub> stubs = myStub.getChildrenStubs();
        return ContainerUtil.mapNotNull(stubs, new NullableFunction<DomStub, DomElement>() {
          @Nullable
          @Override
          public DomElement fun(DomStub stub) {
            if (stub instanceof ElementStub && ((ElementStub)stub).isCustom()) {
              EvaluatedXmlName name = new DummyEvaluatedXmlName(stub.getName(), "");
              return new CollectionElementInvocationHandler(name, (CustomDomChildrenDescriptionImpl)description, myManager, (ElementStub)stub).getProxy();
            }
            return null;
          }
        });
      }
    }
    XmlTag tag = getXmlTag();
    if (tag == null) return Collections.emptyList();

    final List<XmlTag> subTags = tagsGetter.fun(this);
    if (subTags.isEmpty()) return Collections.emptyList();

    List<DomElement> elements = new ArrayList<DomElement>(subTags.size());
    for (XmlTag subTag : subTags) {
      final SemKey<? extends DomInvocationHandler> key = description instanceof CustomDomChildrenDescription ? DomManagerImpl.DOM_CUSTOM_HANDLER_KEY : DomManagerImpl.DOM_COLLECTION_HANDLER_KEY;
      final DomInvocationHandler semElement = myManager.getSemService().getSemElement(key, subTag);
      if (semElement == null) {
        myManager.getSemService().getSemElement(key, subTag);
        throw new AssertionError("No child for subTag '" + subTag.getName() + "' in tag '" + tag.getName() +"' using key " + key);
      }
      else {
        elements.add(semElement.getProxy());
      }
    }
    return Collections.unmodifiableList(elements);
  }

  private static class StableCopyFactory<T extends DomElement> implements NullableFactory<T> {
    private final SmartPsiElementPointer<XmlTag> myPointer;
    private final Type myType;
    private final Class<? extends DomInvocationHandler> myHandlerClass;

    public StableCopyFactory(final SmartPsiElementPointer<XmlTag> pointer,
                             final Type type, final Class<? extends DomInvocationHandler> aClass) {
      myPointer = pointer;
      myType = type;
      myHandlerClass = aClass;
    }

    @Override
    public T create() {
      final XmlTag tag = myPointer.getElement();
      if (tag == null || !tag.isValid()) return null;

      final DomElement element = DomManager.getDomManager(tag.getProject()).getDomElement(tag);
      if (element == null || !element.getDomElementType().equals(myType)) return null;

      final DomInvocationHandler handler = DomManagerImpl.getDomInvocationHandler(element);
      if (handler == null || !handler.getClass().equals(myHandlerClass)) return null;

      return (T)element;
    }
  }

  public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || !o.getClass().equals(getClass())) return false;

    final DomInvocationHandler that = (DomInvocationHandler)o;
    if (!myChildDescription.equals(that.myChildDescription)) return false;
    if (!getParentStrategy().equals(that.getParentStrategy())) return false;

    return true;
  }

  public int hashCode() {
    return myChildDescription.hashCode();
  }
}