private void setupPanels(@Nullable ProjectTemplate template) {

    restorePanel(myNamePathComponent, 4);
    restorePanel(myModulePanel, myWizardContext.isCreatingNewProject() ? 8 : 6);
    restorePanel(myExpertPanel, myWizardContext.isCreatingNewProject() ? 1 : 0);
    mySettingsStep = myModuleBuilder == null ? null : myModuleBuilder.modifySettingsStep(this);

    String description = null;
    if (template != null) {
      description = template.getDescription();
      if (StringUtil.isNotEmpty(description)) {
        StringBuilder sb = new StringBuilder("<html><body><font ");
        sb.append(SystemInfo.isMac ? "" : "face=\"Verdana\" size=\"-1\"").append('>');
        sb.append(description).append("</font></body></html>");
        description = sb.toString();
        myDescriptionPane.setText(description);
      }
    }

    myExpertPlaceholder.setVisible(
        !(myModuleBuilder instanceof TemplateModuleBuilder)
            && myExpertPanel.getComponentCount() > 0);
    for (int i = 0; i < 6; i++) {
      myModulePanel.getComponent(i).setVisible(!(myModuleBuilder instanceof EmptyModuleBuilder));
    }
    myDescriptionPanel.setVisible(StringUtil.isNotEmpty(description));

    mySettingsPanel.revalidate();
    mySettingsPanel.repaint();
  }
  @NotNull
  private static String findMainClass(VirtualFile gradleHome, VirtualFile script, Project project) {
    final String userDefined = System.getProperty("gradle.launcher.class");
    if (StringUtil.isNotEmpty(userDefined)) {
      return userDefined;
    }

    VirtualFile launcher = gradleHome.findFileByRelativePath("bin/gradle");
    if (launcher == null) {
      launcher = gradleHome.findFileByRelativePath("bin/gradle.bat");
    }
    if (launcher != null) {
      try {
        final String text = StringUtil.convertLineSeparators(VfsUtilCore.loadText(launcher));
        final Matcher matcher = MAIN_CLASS_NAME_PATTERN.matcher(text);
        if (matcher.find()) {
          String candidate = matcher.group(1);
          if (StringUtil.isNotEmpty(candidate)) {
            return candidate;
          }
        }
      } catch (IOException ignored) {
      }
    }

    final PsiFile grFile = PsiManager.getInstance(project).findFile(script);
    if (grFile != null
        && JavaPsiFacade.getInstance(project)
                .findClass("org.gradle.BootstrapMain", grFile.getResolveScope())
            != null) {
      return "org.gradle.BootstrapMain";
    }

    return "org.gradle.launcher.GradleMain";
  }
  protected boolean doSetIcon(
      DefaultMutableTreeNode node, @Nullable String path, Component component) {
    if (StringUtil.isNotEmpty(path) && !new File(path).isFile()) {
      Messages.showErrorDialog(
          component,
          IdeBundle.message("error.file.not.found.message", path),
          IdeBundle.message("title.choose.action.icon"));
      return false;
    }

    String actionId = getActionId(node);
    if (actionId == null) return false;

    final AnAction action = ActionManager.getInstance().getAction(actionId);
    if (action != null && action.getTemplatePresentation() != null) {
      if (StringUtil.isNotEmpty(path)) {
        Image image = null;
        try {
          image =
              ImageLoader.loadFromStream(
                  VfsUtil.convertToURL(VfsUtil.pathToUrl(path.replace(File.separatorChar, '/')))
                      .openStream());
        } catch (IOException e) {
          LOG.debug(e);
        }
        Icon icon = new File(path).exists() ? IconLoader.getIcon(image) : null;
        if (icon != null) {
          if (icon.getIconWidth() > EmptyIcon.ICON_18.getIconWidth()
              || icon.getIconHeight() > EmptyIcon.ICON_18.getIconHeight()) {
            Messages.showErrorDialog(
                component,
                IdeBundle.message("custom.icon.validation.message"),
                IdeBundle.message("title.choose.action.icon"));
            return false;
          }
          node.setUserObject(Pair.create(actionId, icon));
          mySelectedSchema.addIconCustomization(actionId, path);
        }
      } else {
        node.setUserObject(Pair.create(actionId, null));
        mySelectedSchema.removeIconCustomization(actionId);
        final DefaultMutableTreeNode nodeOnToolbar = findNodeOnToolbar(actionId);
        if (nodeOnToolbar != null) {
          editToolbarIcon(actionId, nodeOnToolbar);
          node.setUserObject(nodeOnToolbar.getUserObject());
        }
      }
      return true;
    }
    return false;
  }
  public static void addTypeAndClassifierAndVersion(
      @NotNull InsertionContext context,
      @NotNull MavenDomDependency dependency,
      @NotNull String groupId,
      @NotNull String artifactId) {
    if (!StringUtil.isEmpty(dependency.getVersion().getStringValue())) return;

    Project project = context.getProject();

    if (!isInsideManagedDependency(dependency)) {
      MavenDomProjectModel model =
          DomUtil.<MavenDomProjectModel>getFileElement(dependency).getRootElement();
      MavenDomDependency managedDependency =
          findManagedDependency(model, project, groupId, artifactId);
      if (managedDependency != null) {
        if (dependency.getClassifier().getXmlTag() == null
            && dependency.getType().getXmlTag() == null) {
          String classifier = managedDependency.getClassifier().getRawText();
          if (StringUtil.isNotEmpty(classifier)) {
            dependency.getClassifier().setStringValue(classifier);
          }
          String type = managedDependency.getType().getRawText();
          if (StringUtil.isNotEmpty(type)) {
            dependency.getType().setStringValue(type);
          }
        }
        return;
      }
    }

    MavenProjectIndicesManager manager = MavenProjectIndicesManager.getInstance(project);

    Set<String> versions = manager.getVersions(groupId, artifactId);
    if (versions.size() == 1) {
      dependency.getVersion().setStringValue(ContainerUtil.getFirstItem(versions));
      return;
    }

    dependency.getVersion().setStringValue("");

    int versionPosition =
        dependency.getVersion().getXmlTag().getValue().getTextRange().getStartOffset();

    context.getEditor().getCaretModel().moveToOffset(versionPosition);

    if (versions.size() > 0) {
      invokeCompletion(context, CompletionType.BASIC);
    }
  }
  @Override
  protected JComponent getRowPresentation(
      ParameterTableModelItemBase<ParameterInfoImpl> item,
      boolean selected,
      final boolean focused) {
    final JPanel panel = new JPanel(new BorderLayout());
    final String typeText = item.typeCodeFragment.getText();
    final String separator =
        StringUtil.repeatSymbol(' ', getTypesMaxLength() - typeText.length() + 1);
    String text = typeText + separator + item.parameter.getName();
    final String defaultValue = item.defaultValueCodeFragment.getText();
    String tail = "";
    if (StringUtil.isNotEmpty(defaultValue)) {
      tail += " default value = " + defaultValue;
    }
    if (item.parameter.isUseAnySingleVariable()) {
      if (StringUtil.isNotEmpty(defaultValue)) {
        tail += ";";
      }
      tail += " Use any var.";
    }
    if (!StringUtil.isEmpty(tail)) {
      text += " //" + tail;
    }
    final EditorTextField field =
        new EditorTextField(" " + text, getProject(), getFileType()) {
          @Override
          protected boolean shouldHaveBorder() {
            return false;
          }
        };

    Font font = EditorColorsManager.getInstance().getGlobalScheme().getFont(EditorFontType.PLAIN);
    font = new Font(font.getFontName(), font.getStyle(), 12);
    field.setFont(font);

    if (selected && focused) {
      panel.setBackground(UIUtil.getTableSelectionBackground());
      field.setAsRendererWithSelection(
          UIUtil.getTableSelectionBackground(), UIUtil.getTableSelectionForeground());
    } else {
      panel.setBackground(UIUtil.getTableBackground());
      if (selected && !focused) {
        panel.setBorder(new DottedBorder(UIUtil.getTableForeground()));
      }
    }
    panel.add(field, BorderLayout.WEST);
    return panel;
  }
示例#6
0
  @NotNull
  public PsiReference[] getReferences() {
    ProgressManager.checkCanceled();
    final ASTNode startTagName = XmlChildRole.START_TAG_NAME_FINDER.findChild(this);
    if (startTagName == null) return PsiReference.EMPTY_ARRAY;
    final ASTNode endTagName = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(this);
    List<PsiReference> refs = new ArrayList<PsiReference>();
    String prefix = getNamespacePrefix();

    TagNameReference startTagRef =
        TagNameReference.createTagNameReference(this, startTagName, true);
    refs.add(startTagRef);
    if (prefix.length() > 0) {
      refs.add(createPrefixReference(startTagName, prefix, startTagRef));
    }
    if (endTagName != null) {
      TagNameReference endTagRef = TagNameReference.createTagNameReference(this, endTagName, false);
      refs.add(endTagRef);
      prefix = XmlUtil.findPrefixByQualifiedName(endTagName.getText());
      if (StringUtil.isNotEmpty(prefix)) {
        refs.add(createPrefixReference(endTagName, prefix, endTagRef));
      }
    }

    // ArrayList.addAll() makes a clone of the collection
    //noinspection ManualArrayToCollectionCopy
    for (PsiReference ref :
        ReferenceProvidersRegistry.getReferencesFromProviders(this, XmlTag.class)) {
      refs.add(ref);
    }

    return ContainerUtil.toArray(refs, new PsiReference[refs.size()]);
  }
  private boolean hideAutopopupIfMeaningless() {
    if (!myLookup.isLookupDisposed()
        && isAutopopupCompletion()
        && !myLookup.isSelectionTouched()
        && !myLookup.isCalculating()) {
      myLookup.refreshUi(true);
      final List<LookupElement> items = myLookup.getItems();

      for (LookupElement item : items) {
        if (!myLookup.itemPattern(item).equals(item.getLookupString())) {
          return false;
        }

        if (item.isValid()) {
          final LookupElementPresentation presentation = new LookupElementPresentation();
          item.renderElement(presentation);
          if (StringUtil.isNotEmpty(presentation.getTailText())) {
            return false;
          }
        }
      }

      myLookup.hideLookup(false);
      LOG.assertTrue(CompletionServiceImpl.getCompletionService().getCurrentCompletion() == null);
      CompletionServiceImpl.setCompletionPhase(new CompletionPhase.EmptyAutoPopup(this));
      return true;
    }
    return false;
  }
 @Override
 public boolean shouldCreateStub(ASTNode node) {
   PsiElement element = node.getPsi();
   return element instanceof PerlMooseAugmentStatement
       && element.isValid()
       && StringUtil.isNotEmpty(((PerlMooseAugmentStatement) element).getSubName());
 }
示例#9
0
  public void setText(String value) {
    try {
      XmlText text = null;
      if (StringUtil.isNotEmpty(value)) {
        final XmlText[] texts = getTextElements();
        if (texts.length == 0) {
          text =
              (XmlText)
                  myTag.add(
                      XmlElementFactory.getInstance(myTag.getProject()).createDisplayText("x"));
        } else {
          text = texts[0];
        }
        text.setValue(value);
      }

      if (myElements.length > 0) {
        for (final XmlTagChild child : myElements) {
          if (child != text) {
            child.delete();
          }
        }
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  private static Collection<FqName> computeSuggestions(@NotNull JetSimpleNameExpression element) {
    final PsiFile file = element.getContainingFile();
    if (!(file instanceof JetFile)) {
      return Collections.emptyList();
    }

    final String referenceName = element.getReferencedName();

    if (!StringUtil.isNotEmpty(referenceName)) {
      return Collections.emptyList();
    }

    assert referenceName != null;

    List<FqName> result = Lists.newArrayList();
    result.addAll(getClassNames(referenceName, (JetFile) file));
    result.addAll(getJetTopLevelFunctions(referenceName, element, file.getProject()));
    result.addAll(getJetExtensionFunctions(referenceName, element, file.getProject()));

    return Collections2.filter(
        result,
        new Predicate<FqName>() {
          @Override
          public boolean apply(@Nullable FqName fqName) {
            assert fqName != null;
            return ImportInsertHelper.doNeedImport(
                new ImportPath(fqName, false), null, (JetFile) file);
          }
        });
  }
 protected static void setRunnerPath(
     Project project, GeneralCommandLine commandLine, PythonRunParams config) {
   String interpreterPath = getInterpreterPath(project, config);
   if (StringUtil.isNotEmpty(interpreterPath)) {
     commandLine.setExePath(FileUtil.toSystemDependentName(interpreterPath));
   }
 }
 public TestDataReferenceCollector(@Nullable String testDataPath, String testName) {
   if (StringUtil.isNotEmpty(testDataPath)
       && StringUtil.endsWithChar(testDataPath, File.separatorChar)) {
     testDataPath += File.separatorChar;
   }
   myTestDataPath = testDataPath;
   myTestName = testName;
 }
 private boolean matches(@NotNull String text) {
   if (isUnitTest) {
     final SpeedSearchComparator comparator = mySpeedSearch.getComparator();
     return StringUtil.isNotEmpty(myTestSearchFilter)
         && comparator.matchingFragments(myTestSearchFilter, text) != null;
   }
   return mySpeedSearch.matchingFragments(text) != null;
 }
 @Override
 public Iterable<TextRange> matchingFragments(@NotNull String text) {
   if (!isPopupActive()) return null;
   final SpeedSearchComparator comparator = getComparator();
   final String recentSearchText = comparator.getRecentSearchText();
   return StringUtil.isNotEmpty(recentSearchText)
       ? comparator.matchingFragments(recentSearchText, text)
       : null;
 }
 public static void addJavaHome(@NotNull JavaParameters params, @NotNull Module module) {
   final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
   if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
     String path = StringUtil.trimEnd(sdk.getHomePath(), File.separator);
     if (StringUtil.isNotEmpty(path)) {
       params.addEnv("JAVA_HOME", FileUtil.toSystemDependentName(path));
     }
   }
 }
 public static void openTipInBrowser(
     String tipFileName, JEditorPane browser, Class providerClass) {
   TipAndTrickBean tip = TipAndTrickBean.findByFileName(tipFileName);
   if (tip == null && StringUtil.isNotEmpty(tipFileName)) {
     tip = new TipAndTrickBean();
     tip.fileName = tipFileName;
   }
   openTipInBrowser(tip, browser);
 }
 public String suggestBranchName(Task task) {
   if (task.isIssue() && StringUtil.isNotEmpty(task.getNumber())) {
     return task.getId().replace(' ', '-');
   } else {
     String summary = task.getSummary();
     List<String> words = StringUtil.getWordsIn(summary);
     String[] strings = ArrayUtil.toStringArray(words);
     return StringUtil.join(strings, 0, Math.min(2, strings.length), "-");
   }
 }
 private static void suggestCollectionUtilities(
     CompletionParameters parameters, final CompletionResultSet result, PsiElement position) {
   if (StringUtil.isNotEmpty(result.getPrefixMatcher().getPrefix())) {
     for (ExpectedTypeInfo info : JavaSmartCompletionContributor.getExpectedTypes(parameters)) {
       new CollectionsUtilityMethodsProvider(
               position, info.getType(), info.getDefaultType(), result)
           .addCompletions(true);
     }
   }
 }
 public boolean satisfies(@NotNull PsiElement element, @NotNull ResolveState state) {
   final String name = PsiUtilCore.getName(element);
   if (StringUtil.isNotEmpty(name) && (myMatcher == null || myMatcher.value(name))) {
     if (myFilter.isClassAcceptable(element.getClass())
         && myFilter.isAcceptable(
             new CandidateInfo(element, state.get(PsiSubstitutor.KEY)), myElement)) {
       return true;
     }
   }
   return false;
 }
  @NotNull
  private static XmlFileHeader calcXmlFileHeader(final PsiFile file) {

    // if (file.getFileType() == XmlFileType.INSTANCE) {
    //  VirtualFile virtualFile = file.getVirtualFile();
    //  if (virtualFile instanceof VirtualFileWithId) {
    //    ObjectStubTree tree = StubTreeLoader.getInstance().readFromVFile(file.getProject(),
    // virtualFile);
    //    if (tree != null) {
    //      return ((FileStub)tree.getRoot()).getHeader();
    //    }
    //  }
    // }
    if (file instanceof XmlFile && file.getNode().isParsed()) {
      final XmlDocument document = ((XmlFile) file).getDocument();
      if (document != null) {
        String publicId = null;
        String systemId = null;
        final XmlProlog prolog = document.getProlog();
        if (prolog != null) {
          final XmlDoctype doctype = prolog.getDoctype();
          if (doctype != null) {
            publicId = doctype.getPublicId();
            systemId = doctype.getSystemId();
            if (systemId == null) {
              systemId = doctype.getDtdUri();
            }
          }
        }

        final XmlTag tag = document.getRootTag();
        if (tag != null) {
          String localName = tag.getLocalName();
          if (StringUtil.isNotEmpty(localName)) {
            if (tag.getPrevSibling() instanceof PsiErrorElement) {
              return XmlFileHeader.EMPTY;
            }

            String psiNs = tag.getNamespace();
            return new XmlFileHeader(
                localName,
                psiNs == XmlUtil.EMPTY_URI || Comparing.equal(psiNs, systemId) ? null : psiNs,
                publicId,
                systemId);
          }
        }
      }
      return XmlFileHeader.EMPTY;
    }

    if (!file.isValid()) return XmlFileHeader.EMPTY;
    return NanoXmlUtil.parseHeader(file);
  }
 @NotNull
 @Override
 public GrReferenceListStub createStub(@NotNull T psi, StubElement parentStub) {
   List<String> refNames = new ArrayList<>();
   for (GrCodeReferenceElement element : psi.getReferenceElementsGroovy()) {
     final String name = GrStubUtils.getReferenceName(element);
     if (StringUtil.isNotEmpty(name)) {
       refNames.add(name);
     }
   }
   return new GrReferenceListStub(parentStub, this, ArrayUtil.toStringArray(refNames));
 }
  @Nullable
  public static String getReferenceSignature(
      FunctionReference functionReference, char trimKey, int equalParameterCount) {

    String refSignature = functionReference.getSignature();
    if (StringUtil.isEmpty(refSignature)) {
      return null;
    }

    PsiElement[] parameters = functionReference.getParameters();
    if (parameters.length != equalParameterCount) {
      return null;
    }

    PsiElement parameter = parameters[0];

    // we already have a string value
    if ((parameter instanceof StringLiteralExpression)) {
      String param = ((StringLiteralExpression) parameter).getContents();
      if (StringUtil.isNotEmpty(param)) {
        return refSignature + trimKey + param;
      }

      return null;
    }

    // whitelist here; we can also provide some more but think of performance
    // Service::NAME, $this->name and Entity::CLASS;
    if (parameter instanceof PhpReference
        && (parameter instanceof ClassConstantReference || parameter instanceof FieldReference)) {
      String signature = ((PhpReference) parameter).getSignature();
      if (StringUtil.isNotEmpty(signature)) {
        return refSignature + trimKey + signature;
      }

      return null;
    }

    return null;
  }
示例#23
0
  private void updateRightPanel() {
    setOKActionEnabled(myCurrentTemplateItem != null);

    String description =
        myCurrentTemplateItem != null ? myCurrentTemplateItem.getDescription() : null;
    if (StringUtil.isNotEmpty(description)) {
      StringBuilder sb = new StringBuilder("<html><body><font face=\"Verdana\" ");
      sb.append(SystemInfo.isMac ? "" : "size=\"-1\"").append('>');
      sb.append(description).append("</font></body></html>");
      description = sb.toString();
    }
    myDescriptionPane.setText(description);
    myDescriptionPanel.setVisible(description != null);

    JComponent component =
        myCurrentTemplateItem != null ? myCurrentTemplateItem.getSettings() : null;
    myTemplateSettings.removeAll();
    if (component != null) {
      myTemplateSettings.add(
          component,
          new GridConstraints(
              0,
              0,
              1,
              1,
              GridConstraints.ANCHOR_NORTHWEST,
              GridConstraints.FILL_BOTH,
              GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
              GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
              null,
              null,
              null));
      myTemplateSettings.add(
          myProjectFormatPanel.getPanel(),
          new GridConstraints(
              1,
              0,
              1,
              1,
              GridConstraints.ANCHOR_NORTHWEST,
              GridConstraints.FILL_HORIZONTAL,
              GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
              GridConstraints.SIZEPOLICY_FIXED,
              null,
              null,
              null,
              1));
    }
    if (myCurrentTemplateItem != null)
      myCurrentTemplateItem.setNewProjectPath(myProjectPath.getPath());
    myTemplateSettingsHolder.setVisible(component != null);
  }
 public static String[] getAnnotationNames(PsiModifierListOwner psi) {
   List<String> annoNames = ContainerUtil.newArrayList();
   final PsiModifierList modifierList = psi.getModifierList();
   if (modifierList instanceof GrModifierList) {
     for (GrAnnotation annotation : ((GrModifierList) modifierList).getRawAnnotations()) {
       final String name = annotation.getShortName();
       if (StringUtil.isNotEmpty(name)) {
         annoNames.add(name);
       }
     }
   }
   return ArrayUtil.toStringArray(annoNames);
 }
示例#25
0
 @Override
 public boolean isApplicable(PsiFile file, int offset, boolean wrapping) {
   PostfixTemplatesSettings settings = PostfixTemplatesSettings.getInstance();
   if (wrapping
       || file == null
       || settings == null
       || !settings.isPostfixTemplatesEnabled()
       || PsiUtilCore.getLanguageAtOffset(file, offset) != JavaLanguage.INSTANCE) {
     return false;
   }
   return StringUtil.isNotEmpty(
       computeTemplateKeyWithoutContextChecking(file.getText(), offset + 1));
 }
示例#26
0
  public static void addJavaHome(@NotNull JavaParameters params, @NotNull Module module) {
    final Sdk sdk = ModuleUtilCore.getSdk(module, JavaModuleExtensionImpl.class);
    if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
      String path = StringUtil.trimEnd(sdk.getHomePath(), File.separator);
      if (StringUtil.isNotEmpty(path)) {
        Map<String, String> env = params.getEnv();
        if (env == null) {
          env = new HashMap<String, String>();
          params.setEnv(env);
        }

        env.put("JAVA_HOME", FileUtil.toSystemDependentName(path));
      }
    }
  }
 private static boolean reportError(ErrorState state, PsiBuilder builder_, boolean force) {
   String expectedText = state.getExpectedText(builder_);
   boolean notEmpty = StringUtil.isNotEmpty(expectedText);
   if (force || notEmpty) {
     final String gotText =
         builder_.eof()
             ? "unexpected end of file"
             : notEmpty
                 ? "got '" + builder_.getTokenText() + "'"
                 : "'" + builder_.getTokenText() + "' unexpected";
     builder_.error(expectedText + gotText);
     return true;
   }
   return false;
 }
示例#28
0
 @Nullable
 private static String getQuickNavigateInfo(PsiElement element) {
   final String name =
       ElementDescriptionUtil.getElementDescription(element, UsageViewShortNameLocation.INSTANCE);
   if (StringUtil.isEmpty(name)) return null;
   final String typeName =
       ElementDescriptionUtil.getElementDescription(element, UsageViewTypeLocation.INSTANCE);
   final PsiFile file = element.getContainingFile();
   final StringBuilder sb = new StringBuilder();
   if (StringUtil.isNotEmpty(typeName)) sb.append(typeName).append(" ");
   sb.append("\"").append(name).append("\"");
   if (file != null && file.isPhysical()) {
     sb.append(" [").append(file.getName()).append("]");
   }
   return sb.toString();
 }
  public static boolean isEnabled(VirtualFile virtualFile) {
    boolean enabled = true;
    if (virtualFile != null) {
      // FileMode mode = modeFromFile(virtualFile);
      /*if (mode != null) {
          enabled = false;
      } else*/
      if (!virtualFile.isDirectory()) {
        FileType fileType = FileTypeManager.getInstance().getFileTypeByFile(virtualFile);
        if (StringUtil.isNotEmpty(virtualFile.getExtension()) && fileType.isBinary()) {
          enabled = false;
        }
      }
    }

    return enabled;
  }
 private static boolean reportError(
     PsiBuilder builder,
     ErrorState state,
     Frame frame,
     IElementType elementType,
     boolean force,
     boolean advance) {
   String expectedText = state.getExpectedText(builder);
   boolean notEmpty = StringUtil.isNotEmpty(expectedText);
   if (force || notEmpty || advance) {
     String gotText =
         builder.eof()
             ? "unexpected end of file"
             : notEmpty
                 ? "got '" + builder.getTokenText() + "'"
                 : "'" + builder.getTokenText() + "' unexpected";
     String message = expectedText + gotText;
     if (advance) {
       PsiBuilder.Marker mark = builder.mark();
       builder.advanceLexer();
       mark.error(message);
     } else if (!force) {
       PsiBuilder.Marker extensionMarker = null;
       IElementType extensionTokenType = null;
       PsiBuilderImpl.ProductionMarker latestDoneMarker =
           elementType == null
               ? null
               : (PsiBuilderImpl.ProductionMarker) builder.getLatestDoneMarker();
       if (latestDoneMarker != null
           && frame.position >= latestDoneMarker.getStartIndex()
           && frame.position <= latestDoneMarker.getEndIndex()) {
         extensionMarker = ((PsiBuilder.Marker) latestDoneMarker).precede();
         extensionTokenType = latestDoneMarker.getTokenType();
         ((PsiBuilder.Marker) latestDoneMarker).drop();
       }
       builder.error(message);
       if (extensionMarker != null) extensionMarker.done(extensionTokenType);
     } else {
       builder.error(message);
     }
     builder.eof(); // skip whitespaces
     frame.errorReportedAt = builder.rawTokenIndex();
     return true;
   }
   return false;
 }