in src/org/intellij/grammar/refactor/BnfIntroduceTokenHandler.java [221:276]
private static BnfListEntry addTokenDefinition(Project project,
BnfFile bnfFile,
String tokenName,
String tokenText,
Set<String> tokenNames) {
String fixedTokenName = new UniqueNameGenerator(tokenNames, null).generateUniqueName(StringUtil.notNullize(tokenName, "token"));
String newAttrText = "tokens = [\n " + fixedTokenName + "=" + StringUtil.notNullize(tokenText, "\"\"") + "\n ]";
BnfAttr newAttr = BnfElementFactory.createAttributeFromText(project, newAttrText);
BnfAttrs attrs = ContainerUtil.getFirstItem(bnfFile.getAttributes());
BnfAttr tokensAttr = null;
if (attrs == null) {
attrs = (BnfAttrs) bnfFile.addAfter(newAttr.getParent(), null);
bnfFile.addAfter(BnfElementFactory.createLeafFromText(project, "\n"), attrs);
tokensAttr = attrs.getAttrList().get(0);
BnfValueList attrExpr = (BnfValueList)Objects.requireNonNull(tokensAttr.getExpression());
return attrExpr.getListEntryList().get(0);
}
else {
for (BnfAttr attr : attrs.getAttrList()) {
if (KnownAttribute.TOKENS.getName().equals(attr.getName())) {
tokensAttr = attr;
}
}
if (tokensAttr == null) {
List<BnfAttr> attrList = attrs.getAttrList();
PsiElement anchor = attrList.isEmpty() ? attrs.getFirstChild() : attrList.get(attrList.size() - 1);
newAttr = (BnfAttr) attrs.addAfter(newAttr, anchor);
attrs.addAfter(BnfElementFactory.createLeafFromText(project, "\n "), anchor);
BnfValueList attrExpr = (BnfValueList)Objects.requireNonNull(newAttr.getExpression());
return attrExpr.getListEntryList().get(0);
}
else {
BnfExpression expression = tokensAttr.getExpression();
List<BnfListEntry> entryList = expression instanceof BnfValueList ? ((BnfValueList) expression).getListEntryList() : null;
if (entryList == null || entryList.isEmpty()) {
tokensAttr = (BnfAttr)tokensAttr.replace(newAttr);
BnfValueList attrExpr = (BnfValueList)Objects.requireNonNull(tokensAttr.getExpression());
return attrExpr.getListEntryList().get(0);
}
else {
for (BnfListEntry entry : entryList) {
PsiElement id = entry.getId();
if (id != null && id.getText().equals(tokenName)) {
return entry;
}
}
BnfValueList attrExpr = (BnfValueList)Objects.requireNonNull(newAttr.getExpression());
BnfListEntry newValue = attrExpr.getListEntryList().get(0);
PsiElement anchor = entryList.get(entryList.size() - 1);
newValue = (BnfListEntry) expression.addAfter(newValue, anchor);
expression.addAfter(BnfElementFactory.createLeafFromText(project, "\n "), anchor);
return newValue;
}
}
}
}