public static PsiFile createFromTemplate(
      final PsiDirectory directory,
      final String name,
      String fileName,
      String templateName,
      @NonNls String... parameters)
      throws IncorrectOperationException {
    log.debug("createFromTemplate: dir:" + directory + ", filename: " + fileName);

    final FileTemplate template = FileTemplateManager.getInstance().getTemplate(templateName);

    Properties properties =
        new Properties(FileTemplateManager.getInstance().getDefaultProperties());

    String text;

    try {
      text = template.getText(properties);
    } catch (Exception e) {
      throw new RuntimeException(
          "Unable to load template for "
              + FileTemplateManager.getInstance().internalTemplateToSubject(templateName),
          e);
    }

    final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());

    log.debug("Create file from text");
    final PsiFile file = factory.createFileFromText(fileName, MoonFileType.MOON_FILE_TYPE, text);

    log.debug("Adding file to directory");
    return (PsiFile) directory.add(file);
  }
  @Nullable
  private XmlFile createAnnotationsXml(
      @NotNull VirtualFile root, @NonNls @NotNull String packageName) {
    final String[] dirs = packageName.split("[\\.]");
    for (String dir : dirs) {
      if (dir.isEmpty()) break;
      VirtualFile subdir = root.findChild(dir);
      if (subdir == null) {
        try {
          subdir = root.createChildDirectory(null, dir);
        } catch (IOException e) {
          LOG.error(e);
        }
      }
      root = subdir;
    }
    final PsiDirectory directory = myPsiManager.findDirectory(root);
    if (directory == null) return null;

    final PsiFile psiFile = directory.findFile(ANNOTATIONS_XML);
    if (psiFile instanceof XmlFile) {
      return (XmlFile) psiFile;
    }

    try {
      final PsiFileFactory factory = PsiFileFactory.getInstance(myPsiManager.getProject());
      return (XmlFile)
          directory.add(
              factory.createFileFromText(ANNOTATIONS_XML, XmlFileType.INSTANCE, "<root></root>"));
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    return null;
  }
示例#3
0
  public static PsiElement[] parsePattern(
      Project project,
      String context,
      String pattern,
      FileType fileType,
      Language language,
      String extension,
      boolean physical) {
    int offset = context.indexOf(PATTERN_PLACEHOLDER);

    final int patternLength = pattern.length();
    final String patternInContext = context.replace(PATTERN_PLACEHOLDER, pattern);

    final String ext = extension != null ? extension : fileType.getDefaultExtension();
    final String name = "__dummy." + ext;
    final PsiFileFactory factory = PsiFileFactory.getInstance(project);

    final PsiFile file =
        language == null
            ? factory.createFileFromText(
                name, fileType, patternInContext, LocalTimeCounter.currentTime(), physical, true)
            : factory.createFileFromText(name, language, patternInContext, physical, true);
    if (file == null) {
      return PsiElement.EMPTY_ARRAY;
    }

    final List<PsiElement> result = new ArrayList<PsiElement>();

    PsiElement element = file.findElementAt(offset);
    if (element == null) {
      return PsiElement.EMPTY_ARRAY;
    }

    PsiElement topElement = element;
    element = element.getParent();

    while (element != null) {
      if (element.getTextRange().getStartOffset() == offset
          && element.getTextLength() <= patternLength) {
        topElement = element;
      }
      element = element.getParent();
    }

    if (topElement instanceof PsiFile) {
      return topElement.getChildren();
    }

    final int endOffset = offset + patternLength;
    result.add(topElement);
    topElement = topElement.getNextSibling();

    while (topElement != null && topElement.getTextRange().getEndOffset() <= endOffset) {
      result.add(topElement);
      topElement = topElement.getNextSibling();
    }

    return result.toArray(new PsiElement[result.size()]);
  }
 public static ASTNode createSimpleNodeWithText(String text, Project project) {
   assert !text.contains(" ") : "name cannot contain white spaces";
   PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(project);
   PbFile dummyFile =
       (PbFile)
           psiFileFactory.createFileFromText(
               "DUMMY_SET_NAME", PbFileType.PROTOBUF_FILE_TYPE, "message " + text + " {}");
   PbMessageDef dummyMessage = (PbMessageDef) PbPsiUtil.getChild(dummyFile, 0, true, true, false);
   PsiElement newNameElement = dummyMessage.getNameElement();
   return newNameElement.getNode();
 }
示例#5
0
 @NotNull
 private static PsiFile copyFile(
     @NotNull PsiFile file, @NotNull StringBuilder fileContentWithoutKey) {
   final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(file.getProject());
   PsiFile copy =
       psiFileFactory.createFileFromText(
           file.getName(), file.getFileType(), fileContentWithoutKey);
   VirtualFile vFile = copy.getVirtualFile();
   if (vFile != null) {
     vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
   }
   return copy;
 }
  public PsiElement createFromTemplate(
      final Project project,
      final PsiDirectory directory,
      String fileName,
      final FileTemplate template,
      final String templateText,
      final Properties props)
      throws IncorrectOperationException {
    fileName = checkAppendExtension(fileName, template);

    if (FileTypeManager.getInstance().isFileIgnored(fileName)) {
      throw new IncorrectOperationException(
          "This filename is ignored (Settings | File Types | Ignore files and folders)");
    }

    directory.checkCreateFile(fileName);
    PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, templateText);

    if (template.isReformatCode()) {
      CodeStyleManager.getInstance(project).reformat(file);
    }

    file = (PsiFile) directory.add(file);
    return file;
  }
  private void checkPsiIsCorrect(final FileViewProvider key) {
    PsiFile actualPsi = key.getPsi(key.getBaseLanguage());

    PsiTreeDebugBuilder treeDebugBuilder =
        new PsiTreeDebugBuilder().setShowErrorElements(false).setShowWhiteSpaces(false);

    String actualPsiTree = treeDebugBuilder.psiToString(actualPsi);

    String fileName = key.getVirtualFile().getName();
    PsiFile psi =
        PsiFileFactory.getInstance(myProject)
            .createFileFromText(
                fileName,
                FileTypeManager.getInstance().getFileTypeByFileName(fileName),
                actualPsi.getNode().getText(),
                LocalTimeCounter.currentTime(),
                false);

    if (actualPsi.getClass().equals(psi.getClass())) {
      String expectedPsi = treeDebugBuilder.psiToString(psi);

      if (!expectedPsi.equals(actualPsiTree)) {
        myReformatElements.clear();
        assert expectedPsi.equals(actualPsiTree)
            : "Refactored psi should be the same as result of parsing";
      }
    }
  }
示例#8
0
  public static List<PsiElement> createExpressionFromText(Project project, @NonNls String text)
      throws IncorrectOperationException {
    // XXX why we need this?
    // ParserDefinition def = ParserFileType.PARSER_FILE_TYPE.getLanguage().getParserDefinition();
    // assert def != null;

    StringBuilder builder = new StringBuilder("@main[]\n");
    builder.append(text).append("\n");

    final PsiFile dummyFile =
        PsiFileFactory.getInstance(project)
            .createFileFromText(
                DUMMY + ParserFileType.PARSER_FILE_TYPE.getDefaultExtension(), builder.toString());

    ParserMethod method = PsiTreeUtil.getChildOfType(dummyFile, ParserMethod.class);
    PsiElement[] children = method.getChildren();

    List<PsiElement> toReturn = new ArrayList<PsiElement>();

    for (PsiElement element : children) {
      if (element instanceof ParserParameterList || element.getText().equals("\n")) continue;
      toReturn.add(element);
    }

    return toReturn;
  }
  @Nullable
  private Location buildLocation() {
    if (mySelectedTaskProvider == null) {
      return null;
    }
    ExternalTaskExecutionInfo task = mySelectedTaskProvider.produce();
    if (task == null) {
      return null;
    }

    String projectPath = task.getSettings().getExternalProjectPath();
    String name =
        myExternalSystemId.getReadableName()
            + projectPath
            + StringUtil.join(task.getSettings().getTaskNames(), " ");
    // We create a dummy text file instead of re-using external system file in order to avoid
    // clashing with other configuration producers.
    // For example gradle files are enhanced groovy scripts but we don't want to run them via
    // regular IJ groovy script runners.
    // Gradle tooling api should be used for running gradle tasks instead. IJ execution sub-system
    // operates on Location objects
    // which encapsulate PsiElement and groovy runners are automatically applied if that PsiElement
    // IS-A GroovyFile.
    PsiFile file =
        PsiFileFactory.getInstance(myProject)
            .createFileFromText(name, PlainTextFileType.INSTANCE, "nichts");

    return new ExternalSystemTaskLocation(myProject, file, task);
  }
示例#10
0
  @Override
  public PsiElement getMirror() {
    TreeElement mirrorTreeElement = myMirrorFileElement;
    if (mirrorTreeElement == null) {
      synchronized (myMirrorLock) {
        mirrorTreeElement = myMirrorFileElement;
        if (mirrorTreeElement == null) {
          VirtualFile file = getVirtualFile();
          PsiClass[] classes = getClasses();
          String fileName =
              (classes.length > 0 ? classes[0].getName() : file.getNameWithoutExtension())
                  + JavaFileType.DOT_DEFAULT_EXTENSION;

          final Document document = FileDocumentManager.getInstance().getDocument(file);
          assert document != null : file.getUrl();

          CharSequence mirrorText = document.getImmutableCharSequence();
          boolean internalDecompiler = StringUtil.startsWith(mirrorText, BANNER);
          PsiFileFactory factory = PsiFileFactory.getInstance(getManager().getProject());
          PsiFile mirror =
              factory.createFileFromText(fileName, JavaLanguage.INSTANCE, mirrorText, false, false);
          mirror.putUserData(PsiUtil.FILE_LANGUAGE_LEVEL_KEY, getLanguageLevel());

          mirrorTreeElement = SourceTreeToPsiMap.psiToTreeNotNull(mirror);
          try {
            final TreeElement finalMirrorTreeElement = mirrorTreeElement;
            ProgressManager.getInstance()
                .executeNonCancelableSection(
                    new Runnable() {
                      @Override
                      public void run() {
                        setMirror(finalMirrorTreeElement);
                        putUserData(CLS_DOCUMENT_LINK_KEY, document);
                      }
                    });
          } catch (InvalidMirrorException e) {
            //noinspection ThrowableResultOfMethodCallIgnored
            LOG.error(file.getUrl(), internalDecompiler ? e : wrapException(e, file));
          }

          ((PsiFileImpl) mirror).setOriginalFile(this);
          myMirrorFileElement = mirrorTreeElement;
        }
      }
    }
    return mirrorTreeElement.getPsi();
  }
示例#11
0
  public ReplInterpreter(
      @NotNull Disposable disposable, @NotNull CompilerConfiguration configuration) {
    KotlinCoreEnvironment environment =
        KotlinCoreEnvironment.createForProduction(
            disposable, configuration, EnvironmentConfigFiles.JVM_CONFIG_FILES);
    Project project = environment.getProject();
    this.psiFileFactory = (PsiFileFactoryImpl) PsiFileFactory.getInstance(project);
    this.trace = new CliLightClassGenerationSupport.NoScopeRecordCliBindingTrace();
    MutableModuleContext moduleContext =
        TopDownAnalyzerFacadeForJVM.createContextWithSealedModule(project);
    this.module = moduleContext.getModule();

    scriptDeclarationFactory = new ScriptMutableDeclarationProviderFactory();

    FileScopeProvider.AdditionalScopes scopeProvider =
        new FileScopeProvider.AdditionalScopes() {
          @NotNull
          @Override
          public List<JetScope> scopes(@NotNull JetFile file) {
            return lastLineScope != null
                ? new SmartList<JetScope>(lastLineScope)
                : Collections.<JetScope>emptyList();
          }
        };

    ContainerForReplWithJava container =
        DiPackage.createContainerForReplWithJava(
            moduleContext,
            trace,
            scriptDeclarationFactory,
            ProjectScope.getAllScope(project),
            scopeProvider);

    this.topDownAnalysisContext =
        new TopDownAnalysisContext(
            TopDownAnalysisMode.LocalDeclarations,
            DataFlowInfo.EMPTY,
            container.getResolveSession().getDeclarationScopeProvider());
    this.topDownAnalyzer = container.getLazyTopDownAnalyzerForTopLevel();
    this.resolveSession = container.getResolveSession();

    moduleContext.initializeModuleContents(
        new CompositePackageFragmentProvider(
            Arrays.asList(
                container.getResolveSession().getPackageFragmentProvider(),
                container.getJavaDescriptorResolver().getPackageFragmentProvider())));

    List<URL> classpath = Lists.newArrayList();
    for (File file : getJvmClasspathRoots(configuration)) {
      try {
        classpath.add(file.toURI().toURL());
      } catch (MalformedURLException e) {
        throw UtilsPackage.rethrow(e);
      }
    }

    this.classLoader =
        new ReplClassLoader(new URLClassLoader(classpath.toArray(new URL[classpath.size()]), null));
  }
 public static void checkFileStructure(PsiFile file) throws IncorrectOperationException {
   String originalTree = DebugUtil.psiTreeToString(file, false);
   PsiFile dummyFile =
       PsiFileFactory.getInstance(file.getProject())
           .createFileFromText(file.getName(), file.getFileType(), file.getText());
   String reparsedTree = DebugUtil.psiTreeToString(dummyFile, false);
   Assert.assertEquals(reparsedTree, originalTree);
 }
  public void testXml() throws Exception {
    PsiClass aClass = myJavaFacade.findClass("com.Foo", GlobalSearchScope.allScope(myProject));
    doTest(aClass, new String[] {"Test.xml"}, new int[] {32}, new int[] {35});

    final PsiFile nonCodeUsage =
        PsiFileFactory.getInstance(myProject)
            .createFileFromText("a.xml", StdFileTypes.XML, "<root action='com.Foo'/>", 0, true);
    assertTrue(new UsageInfo(nonCodeUsage, 14, 21, true).getNavigationOffset() > 0);
  }
示例#14
0
 protected static PsiFile createLightFile(String fileName, String text)
     throws IncorrectOperationException {
   return PsiFileFactory.getInstance(getProject())
       .createFileFromText(
           fileName,
           FileTypeManager.getInstance().getFileTypeByFileName(fileName),
           text,
           LocalTimeCounter.currentTime(),
           false);
 }
 @NotNull
 private static PsiFile createDummyFile(Project p, String fileText) {
   return PsiFileFactory.getInstance(p)
       .createFileFromText(
           "DUMMY__." + YAMLFileType.YML.getDefaultExtension(),
           YAMLFileType.YML,
           fileText,
           System.currentTimeMillis(),
           false);
 }
示例#16
0
 public static ASTNode createNameIdentifier(Project project, String name)
     throws IncorrectOperationException {
   final PsiFile dummyFile =
       PsiFileFactory.getInstance(project)
           .createFileFromText(
               DUMMY + ParserFileType.PARSER_FILE_TYPE.getDefaultExtension(), name);
   final PsiElement expressionStatement = dummyFile.getFirstChild();
   assert expressionStatement != null;
   return expressionStatement.getNode();
 }
示例#17
0
 public static PsiFile createPseudoPhysicalFile(
     final Project project, final String fileName, final String text)
     throws IncorrectOperationException {
   return PsiFileFactory.getInstance(project)
       .createFileFromText(
           fileName,
           FileTypeManager.getInstance().getFileTypeByFileName(fileName),
           text,
           LocalTimeCounter.currentTime(),
           true);
 }
 public final <T extends DomElement> T createMockElement(
     final Class<T> aClass, final Module module, final boolean physical) {
   final XmlFile file =
       (XmlFile)
           PsiFileFactory.getInstance(myProject)
               .createFileFromText("a.xml", StdFileTypes.XML, "", (long) 0, physical);
   file.putUserData(MOCK_ELEMENT_MODULE, module);
   file.putUserData(MOCK, new Object());
   return getFileElement(
           file, aClass, "I_sincerely_hope_that_nobody_will_have_such_a_root_tag_name")
       .getRootElement();
 }
  public static String getResult(String code) {
    Project project = EnvironmentManager.getEnvironment().getProject();
    JavaToKotlinConverter converter =
        new JavaToKotlinConverter(
            project,
            ConverterSettings.Companion.getDefaultSettings(),
            EmptyJavaToKotlinServices.INSTANCE);
    PsiElementFactory instance = PsiElementFactory.SERVICE.getInstance(project);

    List<PsiElement> inputElements = null;
    PsiFile javaFile =
        PsiFileFactory.getInstance(project)
            .createFileFromText("test.java", JavaLanguage.INSTANCE, code);

    // To create a module
    ResolveUtils.getBindingContext(Collections.EMPTY_LIST, project, false);

    for (PsiElement element : javaFile.getChildren()) {
      if (element instanceof PsiClass) {
        inputElements = Collections.<PsiElement>singletonList(javaFile);
      }
    }

    if (inputElements == null) {
      PsiClass psiClass = instance.createClassFromText(code, javaFile);
      boolean errorsFound = false;
      for (PsiElement element : psiClass.getChildren()) {
        if (element instanceof PsiErrorElement) {
          errorsFound = true;
        }
      }
      if (!errorsFound) {
        inputElements = Arrays.asList(psiClass.getChildren());
      }
    }

    if (inputElements == null) {
      PsiCodeBlock codeBlock = instance.createCodeBlockFromText("{" + code + "}", javaFile);
      PsiElement[] childrenWithoutBraces =
          Arrays.copyOfRange(codeBlock.getChildren(), 1, codeBlock.getChildren().length - 1);
      inputElements = Arrays.asList(childrenWithoutBraces);
    }

    List<JavaToKotlinConverter.ElementResult> resultFormConverter =
        converter.elementsToKotlin(inputElements).getResults();
    String textResult = "";
    for (JavaToKotlinConverter.ElementResult it : resultFormConverter) {
      if (it == null) continue;
      textResult = textResult + it.getText() + "\n";
    }
    textResult = JavaToKotlinTranslator.INSTANCE.prettify(textResult);
    return textResult;
  }
  private static Document createDocument(
      String value,
      @Nullable Language language,
      Project project,
      @NotNull SimpleDocumentCreator documentCreator) {
    if (language != null) {
      final PsiFileFactory factory = PsiFileFactory.getInstance(project);
      final FileType fileType = language.getAssociatedFileType();
      assert fileType != null;

      final long stamp = LocalTimeCounter.currentTime();
      final PsiFile psiFile =
          factory.createFileFromText(
              "Dummy." + fileType.getDefaultExtension(), fileType, value, stamp, true, false);
      documentCreator.customizePsiFile(psiFile);
      final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
      assert document != null;
      return document;
    } else {
      return EditorFactory.getInstance().createDocument(value);
    }
  }
 @Nullable
 private PsiFileSystemItem doResolve(FileIncludeInfo info, PsiFile context) {
   PsiFileImpl psiFile =
       (PsiFileImpl)
           myPsiFileFactory.createFileFromText("dummy.txt", StdFileTypes.PLAIN_TEXT, info.path);
   psiFile.setOriginalFile(context);
   return new FileReferenceSet(psiFile) {
     @Override
     protected boolean useIncludingFileAsContext() {
       return false;
     }
   }.resolve();
 }
 @NotNull
 public static PsiFile createFileFromText(
     @NotNull Project project,
     @NotNull CharSequence text,
     @NotNull LanguageFileType fileType,
     @NotNull VirtualFile file,
     @NotNull String fileName) {
   final Language language = fileType.getLanguage();
   final Language substitutedLanguage =
       LanguageSubstitutors.INSTANCE.substituteLanguage(language, file, project);
   return PsiFileFactory.getInstance(project)
       .createFileFromText(fileName, substitutedLanguage, text, false, false, true, file);
 }
  @Nullable
  private PsiFile createFile(final String text, final String name) {
    if (myTemplate == null || myProject == null) return null;

    final FileType fileType = myVelocityFileType;
    if (fileType == FileTypes.UNKNOWN) return null;

    final PsiFile file =
        PsiFileFactory.getInstance(myProject)
            .createFileFromText(name + ".txt.ft", fileType, text, 0, true);
    file.getViewProvider()
        .putUserData(
            FileTemplateManager.DEFAULT_TEMPLATE_PROPERTIES,
            FileTemplateManager.getInstance().getDefaultProperties(myProject));
    return file;
  }
  @NotNull
  public static PsiElement createBundleFile(
      @NotNull PhpClass bundleClass,
      @NotNull String template,
      @NotNull String className,
      Map<String, String> vars)
      throws Exception {

    VirtualFile directory =
        bundleClass.getContainingFile().getContainingDirectory().getVirtualFile();
    if (fileExists(directory, new String[] {className})) {
      throw new Exception("File already exists");
    }

    String COMPILER_TEMPLATE = "/resources/fileTemplates/" + template + ".php";
    String fileTemplateContent = getFileTemplateContent(COMPILER_TEMPLATE);
    if (fileTemplateContent == null) {
      throw new Exception("Template content error");
    }

    String[] split = className.split("\\\\");

    String ns = bundleClass.getNamespaceName();
    String join = StringUtils.join(Arrays.copyOf(split, split.length - 1), "/");

    vars.put("ns", (ns.startsWith("\\") ? ns.substring(1) : ns) + join.replace("/", "\\"));
    vars.put("class", split[split.length - 1]);
    for (Map.Entry<String, String> entry : vars.entrySet()) {
      fileTemplateContent =
          fileTemplateContent.replace("{{ " + entry.getKey() + " }}", entry.getValue());
    }

    VirtualFile compilerDirectory = getAndCreateDirectory(directory, join);
    if (compilerDirectory == null) {
      throw new Exception("Directory creation failed");
    }

    Project project = bundleClass.getProject();
    PsiFile fileFromText =
        PsiFileFactory.getInstance(project)
            .createFileFromText(
                split[split.length - 1] + ".php", PhpFileType.INSTANCE, fileTemplateContent);
    CodeStyleManager.getInstance(project).reformat(fileFromText);
    return PsiDirectoryFactory.getInstance(project)
        .createDirectory(compilerDirectory)
        .add(fileFromText);
  }
 @Nullable
 private PsiFile createFileCopyWithNewName(VirtualFile vFile, String name) {
   // TODO[ik] remove this. Event handling and generation must be in view providers mechanism since
   // we
   // need to track changes in _all_ psi views (e.g. namespace changes in XML)
   final FileTypeManager instance = FileTypeManager.getInstance();
   if (instance.isFileIgnored(name)) return null;
   final FileType fileTypeByFileName = instance.getFileTypeByFileName(name);
   final Document document = FileDocumentManager.getInstance().getDocument(vFile);
   return PsiFileFactory.getInstance(myManager.getProject())
       .createFileFromText(
           name,
           fileTypeByFileName,
           document != null ? document.getCharsSequence() : "",
           vFile.getModificationStamp(),
           true,
           false);
 }
 @NotNull
 private static XmlFile parseXmlFileInTemplate(
     String templateString, CustomTemplateCallback callback, boolean createPhysicalFile) {
   XmlFile xmlFile =
       (XmlFile)
           PsiFileFactory.getInstance(callback.getProject())
               .createFileFromText(
                   "dummy.xml",
                   StdFileTypes.XML,
                   templateString,
                   LocalTimeCounter.currentTime(),
                   createPhysicalFile);
   VirtualFile vFile = xmlFile.getVirtualFile();
   if (vFile != null) {
     vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
   }
   return xmlFile;
 }
  private static List<PsiElement> getTopLevelRegExpChars(String regExpText, Project project) {
    @SuppressWarnings("deprecation")
    PsiFile file = PsiFileFactory.getInstance(project).createFileFromText("A.regexp", regExpText);
    List<PsiElement> result = null;
    final PsiElement[] children = file.getChildren();

    for (PsiElement child : children) {
      PsiElement[] grandChildren = child.getChildren();
      if (grandChildren.length != 1)
        return Collections
            .emptyList(); // a | b, more than one branch, can not predict in current way

      for (PsiElement grandGrandChild : grandChildren[0].getChildren()) {
        if (result == null) result = new ArrayList<>();
        result.add(grandGrandChild);
      }
    }
    return result != null ? result : Collections.<PsiElement>emptyList();
  }
示例#28
0
  @NotNull
  public static KtFile createFile(
      @NotNull @NonNls final String name, @NotNull String text, @NotNull Project project) {
    String shortName = name.substring(name.lastIndexOf('/') + 1);
    shortName = shortName.substring(shortName.lastIndexOf('\\') + 1);
    LightVirtualFile virtualFile =
        new LightVirtualFile(shortName, KotlinLanguage.INSTANCE, text) {
          @NotNull
          @Override
          public String getPath() {
            // TODO: patch LightVirtualFile
            return "/" + name;
          }
        };

    virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET);
    PsiFileFactoryImpl factory = (PsiFileFactoryImpl) PsiFileFactory.getInstance(project);
    //noinspection ConstantConditions
    return (KtFile) factory.trySetupPsiForFile(virtualFile, KotlinLanguage.INSTANCE, true, false);
  }
  private static Collection<String> suggestKeywords(PsiElement position) {
    TextRange posRange = position.getTextRange();
    BnfFile posFile = (BnfFile) position.getContainingFile();
    BnfRule statement = PsiTreeUtil.getTopmostParentOfType(position, BnfRule.class);
    final TextRange range;
    if (statement != null) {
      range = new TextRange(statement.getTextRange().getStartOffset(), posRange.getStartOffset());
    } else {
      int offset = posRange.getStartOffset();
      for (PsiElement cur = GrammarUtil.getDummyAwarePrevSibling(position);
          cur != null;
          cur = GrammarUtil.getDummyAwarePrevSibling(cur)) {
        if (cur instanceof BnfAttrs) offset = cur.getTextRange().getEndOffset();
        else if (cur instanceof BnfRule) offset = cur.getTextRange().getStartOffset();
        else continue;
        break;
      }
      range = new TextRange(offset, posRange.getStartOffset());
    }
    final String text =
        range.isEmpty()
            ? CompletionInitializationContext.DUMMY_IDENTIFIER
            : range.substring(posFile.getText());

    PsiFile file =
        PsiFileFactory.getInstance(posFile.getProject())
            .createFileFromText("a.bnf", BnfLanguage.INSTANCE, text, true, false);
    int completionOffset = posRange.getStartOffset() - range.getStartOffset();
    GeneratedParserUtilBase.CompletionState state =
        new GeneratedParserUtilBase.CompletionState(completionOffset) {
          @Override
          public String convertItem(Object o) {
            // we do not have other keywords
            return o instanceof String ? (String) o : null;
          }
        };
    file.putUserData(GeneratedParserUtilBase.COMPLETION_STATE_KEY, state);
    TreeUtil.ensureParsed(file.getNode());
    return state.items;
  }
  public void testFileCreation() throws Exception {
    PsiDirectory root = ProjectRootUtil.getAllContentRoots(myProject)[0];

    PsiFile file =
        PsiFileFactory.getInstance(myProject)
            .createFileFromText("New.java", JavaFileType.INSTANCE, "class A{ Object o;}");
    final PsiFile finalFile = file;
    file =
        new WriteAction<PsiFile>() {
          @Override
          protected void run(Result<PsiFile> result) throws Throwable {
            PsiFile res = (PsiFile) root.add(finalFile);
            result.setResult(res);
          }
        }.execute().throwException().getResultObject();
    assertNotNull(file);

    PsiClass objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {"New.java"});
  }