title |
---|
6. PSI Helpers and Utilities |
Helper classes and utilities can be embedded in the code generated by Grammar-Kit.
- bullet item {:toc}
Custom methods in PSI classes are defined separately, and Grammar-Kit embeds them into generated code. Define a utility class with these helper methods:
package org.intellij.sdk.language.psi.impl;
import com.intellij.lang.ASTNode;
public class SimplePsiImplUtil {
public static String getKey(SimpleProperty element) {
ASTNode keyNode = element.getNode().findChildByType(SimpleTypes.KEY);
if (keyNode != null) {
// IMPORTANT: Convert embedded escaped spaces to simple spaces
return keyNode.getText().replaceAll("\\\\ ", " ");
} else {
return null;
}
}
public static String getValue(SimpleProperty element) {
ASTNode valueNode = element.getNode().findChildByType(SimpleTypes.VALUE);
if (valueNode != null) {
return valueNode.getText();
} else {
return null;
}
}
}
The parser generates the SimpleProperty
interface referenced in the code above.
Now the utility class is added to the grammar file via the psiImplUtilClass
attribute.
Add methods for a particular rule to specify which one should be used for PSI classes.
Compare the last line of the grammar below to the previous definition.
{
parserClass="org.intellij.sdk.language.parser.SimpleParser"
extends="com.intellij.extapi.psi.ASTWrapperPsiElement"
psiClassPrefix="Simple"
psiImplClassSuffix="Impl"
psiPackage="org.intellij.sdk.language.psi"
psiImplPackage="org.intellij.sdk.language.psi.impl"
elementTypeHolderClass="org.intellij.sdk.language.psi.SimpleTypes"
elementTypeClass="org.intellij.sdk.language.psi.SimpleElementType"
tokenTypeClass="org.intellij.sdk.language.psi.SimpleTokenType"
psiImplUtilClass="org.intellij.sdk.language.psi.impl.SimplePsiImplUtil"
}
simpleFile ::= item_*
private item_ ::= (property|COMMENT|CRLF)
property ::= (KEY? SEPARATOR VALUE?) | KEY {methods=[getKey getValue]}
After making changes to the grammar, regenerate the parser and PSI classes.
Create a utility class to search PSI elements for defined properties over the project. This utility will be used later when implementing code completion.
{% include /code_samples/simple_language_plugin/src/main/java/org/intellij/sdk/language/SimpleUtil.java %}