Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
* Parser runtime: `MAX_CHILDREN_IN_TREE`, the `DUMMY_BLOCK` chunk size, is now public, so tree-walking code no longer hardcodes it.
* BNF completion: keyword and attribute completion now test dummy blocks against the platform's `DummyBlockType.DummyBlock`.
* Generator: drop the unused annotation import that generated PSI impls picked up from an annotated superclass constructor.
* Generator: generated sources are written with `\n` on every platform, and a CRLF grammar or `classHeader` file no longer inserts a blank line after every `// rule expression` comment [#468](https://github.com/JetBrains/Grammar-Kit/issues/468)
* Generator: grammar and `classHeader` files are decoded by their byte order mark, else as UTF-8, and generated files are encoded to match. Standalone (CLI/Gradle) runs previously followed the JVM default charset, so a non-ASCII grammar produced different bytes on different hosts and a UTF-16 grammar could not be read at all
* Generator: case conversion and number formatting are locale-independent, so generated code no longer varies with the default locale (Turkish `i`/`I`, non-Latin digit systems). Also fixes JFlex keyword completion and the Live Preview token lookup
* Generator CLI: accept forward-slash, root-relative and drive-relative grammar paths - `Main` split the argument on `File.separator` only, so on Windows `out/dir C:/proj/grammars/My.bnf` silently found no grammars. Wildcard matches are also processed in a stable, name-sorted order

## [2023.3.4]

Expand Down
25 changes: 21 additions & 4 deletions bnf-language/src/org/intellij/grammar/LightPsi.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.SyntaxTraverser;
Expand Down Expand Up @@ -115,7 +116,8 @@
*/
public static @Nullable PsiFile parseFile(@NotNull File file, @NotNull ParserDefinition parserDefinition) throws IOException {
String name = file.getName();
String text = FileUtil.loadFile(file);
// bytesToString honours a BOM when the file has one, and strips it; UTF-8 otherwise
String text = CharsetToolkit.bytesToString(FileUtil.loadFileBytes(file), StandardCharsets.UTF_8);

Check warning on line 120 in bnf-language/src/org/intellij/grammar/LightPsi.java

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'com.intellij.openapi.vfs.CharsetToolkit' is marked unstable with @ApiStatus.Internal

Check warning on line 120 in bnf-language/src/org/intellij/grammar/LightPsi.java

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'bytesToString(byte @org.jetbrains.annotations.NotNull \[\], java.nio.charset.@org.jetbrains.annotations.NotNull Charset)' is declared in unstable class 'com.intellij.openapi.vfs.CharsetToolkit' marked with @ApiStatus.Internal
return parseFile(name, text, parserDefinition);
}

Expand Down Expand Up @@ -237,25 +239,40 @@
Init.addKeyedExtension(LanguageParserDefinitions.INSTANCE, language, definition, this);
MockLanguageFileType fileType = new MockLanguageFileType(language, FileUtilRt.getExtension(name));
app.registerFileType(fileType, fileType.getDefaultExtension());
LightVirtualFile file = new LightVirtualFile(name, fileType, text);
LightVirtualFile file = new LightVirtualFile(name, fileType, normalizeText(text));
// The generator encodes its output with the grammar file's charset. A LightVirtualFile would
// otherwise report the JVM default, making generated bytes depend on the host and on
// -Dfile.encoding; standalone runs always read and write UTF-8.
file.setCharset(StandardCharsets.UTF_8);
return ((PsiFileFactoryImpl)PsiFileFactory.getInstance(getProject())).trySetupPsiForFile(file, language, true, false);
}

protected @NotNull ASTNode createAST(@NotNull String text, @NotNull ParserDefinition definition) {
PsiParser parser = definition.createParser(getProject());
Lexer lexer = definition.createLexer(getProject());
PsiBuilderImpl psiBuilder = new PsiBuilderImpl(getProject(), null, definition, lexer, new CharTableImpl(), text, null, null);
PsiBuilderImpl psiBuilder = new PsiBuilderImpl(getProject(), null, definition, lexer, new CharTableImpl(), normalizeText(text), null, null);
return parser.parse(definition.getFileNodeType(), psiBuilder);
}

protected @NotNull SyntaxTraverser<LighterASTNode> parseLight(@NotNull String text, @NotNull ParserDefinition definition) {
LightPsiParser parser = (LightPsiParser)definition.createParser(getProject());
Lexer lexer = definition.createLexer(getProject());
PsiBuilderImpl psiBuilder = new PsiBuilderImpl(getProject(), null, definition, lexer, new CharTableImpl(), text, null, null);
PsiBuilderImpl psiBuilder = new PsiBuilderImpl(getProject(), null, definition, lexer, new CharTableImpl(), normalizeText(text), null, null);
parser.parseLight(definition.getFileNodeType(), psiBuilder);
return SyntaxTraverser.lightTraverser(psiBuilder);
}

/**
* PSI text is {@code \n}-only by platform contract: in the IDE the document normalizes line
* separators before a tree is built. Here the text comes straight from disk, so a CRLF grammar
* would otherwise leave a stray {@code \r} at the end of every PSI line and leak into whatever
* echoes source text back out - notably the {@code // rule expression} comments the parser
* generator emits.
*/
private static @NotNull String normalizeText(@NotNull String text) {
return StringUtil.convertLineSeparators(text);
}

private MockProject getProject() {
return proj.getProject();
}
Expand Down
5 changes: 3 additions & 2 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,6 @@ tasks {
useJUnit()
include("**/BnfTestSuite.class")
isScanForTestClasses = false
ignoreFailures = true
dependsOn("testMain")
}

Expand Down Expand Up @@ -341,7 +340,9 @@ intellijPlatformTesting {
useJUnit()
include("**/MainTest.class")
isScanForTestClasses = false
ignoreFailures = true
// Deliberately not UTF-8: standalone generation must not depend on the JVM default
// charset, so the CLI tests run under one that would expose it.
systemProperty("file.encoding", "ISO-8859-1")
testClassesDirs = files(layout.buildDirectory.dir("instrumented/instrumentTestCode"))
}
sandboxDirectory = layout.buildDirectory.dir("testMain-sandbox")
Expand Down
25 changes: 23 additions & 2 deletions generator/src/org/intellij/grammar/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Stream;
Expand Down Expand Up @@ -133,6 +134,8 @@ private record GrammarPattern(
if (files == null) return List.of();

return Stream.of(files)
// listFiles() order is filesystem-dependent; generate in a stable order instead
.sorted(Comparator.comparing(File::getName))
.filter(f -> !f.isDirectory() && grammarPattern.matcher(f.getName()).matches())
.toList();
}
Expand All @@ -142,13 +145,31 @@ boolean isValid() {
}

static @NotNull Main.GrammarPattern of(@NotNull String grammar) {
int idx = grammar.lastIndexOf(File.separator);
File grammarDir = new File(idx >= 0 ? grammar.substring(0, idx) : ".");
// '/' as well as the host separator: build scripts routinely hand Windows paths with
// forward slashes, which the OS accepts but File.separator alone would not recognize.
int idx = Math.max(grammar.lastIndexOf('/'), grammar.lastIndexOf(File.separatorChar));
File grammarDir = new File(idx >= 0 ? directoryOf(grammar.substring(0, idx)) : ".");
String wildCard = idx >= 0 ? grammar.substring(idx + 1) : grammar;
Pattern grammarPattern = Pattern.compile(convertToJavaPattern(wildCard));
return new GrammarPattern(grammarDir, grammarPattern, wildCard);
}

/**
* Turns the part of the argument before the last separator into a directory that means what
* it says. Everything the separator scan leaves behind is already a directory except the two
* roots: {@code /Grammar.bnf} leaves {@code ""}, which resolves to the working directory
* rather than to the filesystem root, and {@code C:/Grammar.bnf} leaves {@code "C:"}, which
* on Windows is the current directory <em>on drive C</em> rather than the drive root.
* (On other systems {@code "C:"} is an ordinary relative name, and appending a separator
* still names the same directory.)
*/
private static @NotNull String directoryOf(@NotNull String prefix) {
if (prefix.isEmpty()) return File.separator;
return prefix.length() == 2 && prefix.charAt(1) == ':' && Character.isLetter(prefix.charAt(0))
? prefix + File.separator
: prefix;
}

private static @NotNull String convertToJavaPattern(@NotNull String wildcardPattern) {
wildcardPattern = StringUtil.replace(wildcardPattern, ".", "\\.");
wildcardPattern = StringUtil.replace(wildcardPattern, "*?", ".+");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ public static void generateExpressionRoot(ExpressionInfo info, JavaParserGenerat
R.getNextName(R.getFuncName(operator.rule()), 1),
ConsumeType.DEFAULT).render(R);
if (operator.type() == OperatorType.BINARY) {
String argCall = format("%s(%s, %s, %d)", methodName, g.N.builder, g.N.level, rightAssociative ? argPriority - 1 : argPriority);
String argCall = format(Locale.ROOT, "%s(%s, %s, %d)", methodName, g.N.builder, g.N.level, rightAssociative ? argPriority - 1 : argPriority);
g.out("%s = %s;", g.N.result, tailCall == null ? argCall : format("report_error_(%s, %s)", g.N.builder, argCall));
if (tailCall != null) g.out("%s = %s && %s;", g.N.result, tailCall, g.N.result);
}
Expand Down
26 changes: 21 additions & 5 deletions generator/src/org/intellij/grammar/generator/FilePrinter.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,47 @@
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Locale;

final class FilePrinter implements Closeable {
private final @NotNull PrintWriter myOut;
private int myOffset;

public FilePrinter(@NotNull PrintWriter output) {
myOut = output;
public FilePrinter(@NotNull Writer output) {
// PrintWriter for its swallow-the-IOException behaviour, buffered because the writer handed
// over by an OutputOpener need not be. Line breaks come from newLine(), never from println().
myOut = new PrintWriter(new BufferedWriter(output));
myOffset = 0;
}

/**
* Formats the string given the format and args and then
* prints it to the output.
* <p>
* {@link Locale#ROOT}: the formatted text is source code, so {@code %d} must render Latin
* digits whatever the default locale's numbering system is.
*/
public void out(@NotNull String format, Object... args) {
this.out(format.formatted(args));
this.out(String.format(Locale.ROOT, format, args));
}

/**
* Prints the given string to the output.
* Additionally, it manages the indent level appropriately.
* <p>
* Lines are always terminated with {@code \n} rather than the platform separator so that
* generated sources, which are typically committed, are byte-identical on every host OS.
*
* @param output the string to print
*/
public void out(@NotNull String output) {
int length = output.length();
if (length == 0) {
myOut.println();
newLine();
return;
}
boolean newStatement = true;
Expand All @@ -52,7 +63,8 @@ public void out(@NotNull String output) {
if (myOffset > 0) {
myOut.print(StringUtil.repeat(" ", newStatement ? myOffset : myOffset + 1));
}
myOut.println(substring);
myOut.print(substring);
newLine();
if (isComment) {
newStatement = true;
}
Expand All @@ -70,6 +82,10 @@ else if (substring.endsWith("(")) {
}
}

private void newLine() {
myOut.print('\n');
}

/**
* Sets the current offset level of this object to 0.
*/
Expand Down
10 changes: 9 additions & 1 deletion generator/src/org/intellij/grammar/generator/Generator.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.psi.PsiElement;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
Expand Down Expand Up @@ -162,7 +163,14 @@
private String getStringOrFile(String classHeader) {
try {
File file = new File(mySourcePath, classHeader);
if (file.exists()) return FileUtil.loadFile(file);
// bytesToString: a BOM if the file has one, otherwise the grammar's own charset - the same
// one the output is written with, UTF-8 standalone and the project encoding in the IDE.
// convertLineSeparators because out() splits on '\n' only, so a CRLF header file would
// otherwise leave a stray '\r' at the end of every header line of every generated file.
if (file.exists()) {
byte[] bytes = FileUtil.loadFileBytes(file);
return StringUtil.convertLineSeparators(CharsetToolkit.bytesToString(bytes, myFile.getVirtualFile().getCharset()));

Check warning on line 172 in generator/src/org/intellij/grammar/generator/Generator.java

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'bytesToString(byte @org.jetbrains.annotations.NotNull \[\], java.nio.charset.@org.jetbrains.annotations.NotNull Charset)' is declared in unstable class 'com.intellij.openapi.vfs.CharsetToolkit' marked with @ApiStatus.Internal

Check warning on line 172 in generator/src/org/intellij/grammar/generator/Generator.java

View workflow job for this annotation

GitHub Actions / Qodana for JVM

Unstable API Usage

'com.intellij.openapi.vfs.CharsetToolkit' is marked unstable with @ApiStatus.Internal
}
}
catch (IOException ex) {
LOG.error(ex);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1839,7 +1839,7 @@ private void generateElementTypesConverter(String elementTypesConverter,
var generateTokenTypeConversions = G.generateTokenTypes && !mySimpleTokens.isEmpty();
for (int i = 0; i < sortedCompositeTypesArr.length; i++) {
String elementType = sortedCompositeTypesArr[i];
String elementTypeAccessor = "INSTANCE.get" + elementType.substring(0, 1).toUpperCase() + elementType.substring(1) + "()";
String elementTypeAccessor = "INSTANCE.get" + StringUtil.capitalize(elementType) + "()";
out("new %s<%s, %s>(%s.%s, %s.%s)" + (i != sortedCompositeTypesArr.length - 1 || generateTokenTypeConversions ? "," : ""),
shorten(KotlinBnfConstants.KT_PAIR_CLASS),
shorten(KotlinBnfConstants.KT_ELEMENT_TYPE_CLASS), shorten(JavaBnfConstants.IELEMENTTYPE_CLASS),
Expand All @@ -1854,7 +1854,7 @@ private void generateElementTypesConverter(String elementTypesConverter,
String tokenName = ObjectUtils.chooseNotNull(mySimpleTokens.get(tokenText), tokenText);
if (isIgnoredWhitespaceToken(tokenName, tokenText)) continue;
var elementType = getElementType(tokenName);
String elementTypeAccessor = "INSTANCE.get" + elementType.substring(0, 1).toUpperCase() + elementType.substring(1) + "()";
String elementTypeAccessor = "INSTANCE.get" + StringUtil.capitalize(elementType) + "()";
out("new %s<%s, %s>(%s.%s, %s.%s)" + (i != mySimpleTokensArr.length - 1 ? "," : ""),
shorten(KotlinBnfConstants.KT_PAIR_CLASS),
shorten(KotlinBnfConstants.KT_ELEMENT_TYPE_CLASS), shorten(JavaBnfConstants.IELEMENTTYPE_CLASS),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -665,7 +665,7 @@ private void generateExpressionRoot(@NotNull ExpressionInfo info) {
operator.rule(), operator.tail(), R.getNextName(R.getFuncName(operator.rule()), 1), ConsumeType.DEFAULT
).render(R);
if (operator.type() == OperatorType.BINARY) {
String argCall = format("%s(%s, %s, %d)", methodName, N.runtime, N.level, rightAssociative ? argPriority - 1 : argPriority);
String argCall = format(Locale.ROOT, "%s(%s, %s, %d)", methodName, N.runtime, N.level, rightAssociative ? argPriority - 1 : argPriority);
out("%s = %s", N.result, tailCall == null ? argCall : format("%s.report_error_(%s)", N.runtime, argCall));
if (tailCall != null) out("%s = %s && %s", N.result, tailCall, N.result);
}
Expand Down
7 changes: 4 additions & 3 deletions generator/src/org/intellij/grammar/generator/NodeCalls.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;


Expand Down Expand Up @@ -92,7 +93,7 @@ record ConsumeTokensCall(
) implements NodeCall {
@Override
public @NotNull String render(@NotNull NameRenderer nameRenderer) {
return String.format("%s(%s, %d, %s)", methodName, builder, pin, StringUtil.join(tokens, ", "));
return String.format(Locale.ROOT, "%s(%s, %d, %s)", methodName, builder, pin, StringUtil.join(tokens, ", "));
}
}

Expand All @@ -104,7 +105,7 @@ record KotlinConsumeTokensCall(
) implements NodeCall {
@Override
public @NotNull String render(@NotNull NameRenderer nameRenderer) {
return String.format("%s.%s(%d, %s)", stateHolder, methodName, pin, StringUtil.join(tokens, ", "));
return String.format(Locale.ROOT, "%s.%s(%d, %s)", stateHolder, methodName, pin, StringUtil.join(tokens, ", "));
}
}

Expand All @@ -116,7 +117,7 @@ record ExpressionMethodCall(
) implements NodeCall {
@Override
public @NotNull String render(@NotNull NameRenderer nameRenderer) {
return String.format("%s(%s, %s + 1, %d)", methodName, stateHolder, level, priority);
return String.format(Locale.ROOT, "%s(%s, %s + 1, %d)", methodName, stateHolder, level, priority);
}
}

Expand Down
15 changes: 12 additions & 3 deletions generator/src/org/intellij/grammar/generator/OutputOpener.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,25 @@
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;

@FunctionalInterface
public interface OutputOpener {
@NotNull OutputOpener DEFAULT = (className, fileToOpen, myBnfFile) -> {
fileToOpen.getParentFile().mkdirs();
return new PrintWriter(new FileOutputStream(fileToOpen), false, myBnfFile.getVirtualFile().getCharset());
return new OutputStreamWriter(new FileOutputStream(fileToOpen), myBnfFile.getVirtualFile().getCharset());
};

@NotNull PrintWriter openOutput(
/**
* Opens the destination of one generated file.
* <p>
* A {@link Writer}, deliberately not a {@link java.io.PrintWriter}: {@code println} terminates
* lines with the platform separator, and generated sources are committed artifacts that must
* come out byte-identical on every host. Anything written here - a banner, say - spells its
* line breaks {@code "\n"}, and {@link FilePrinter} does the same for the body.
*/
@NotNull Writer openOutput(
@NotNull String className,
@NotNull File fileToOpen,
@NotNull BnfFile myBnfFile
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ enum ConsumeType {
}

public @NotNull String getMethodSuffix() {
return this == DEFAULT ? "" : StringUtil.capitalize(name().toLowerCase());
return this == DEFAULT ? "" : StringUtil.capitalize(StringUtil.toLowerCase(name()));
}

public @NotNull String getMethodName() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.intellij.util.ObjectUtils;
import com.intellij.util.ProcessingContext;
import org.intellij.grammar.parser.GeneratedParserUtilBase;
import org.intellij.grammar.util.Case;
import org.intellij.jflex.psi.*;
import org.intellij.jflex.psi.impl.JFlexFileImpl;
import org.jetbrains.annotations.NotNull;
Expand Down Expand Up @@ -106,7 +107,7 @@ private static Collection<String> suggestKeywords(PsiElement position) {
}

private static LookupElement createKeywordLookupItem(PsiFile psiFile, String keyword) {
LookupElementBuilder builder = LookupElementBuilder.create(keyword.toLowerCase()).withCaseSensitivity(false).bold();
LookupElementBuilder builder = LookupElementBuilder.create(Case.LOWER.apply(keyword)).withCaseSensitivity(false).bold();
boolean braces = keyword.endsWith("{") || keyword.endsWith("}");
if (!braces) {
return keyword.startsWith("%") ? TailTypeDecorator.withTail(builder, TailTypes.spaceType()) : builder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ public Void visitRule(@NotNull BnfRule o) {
}

public static boolean isTokenTextSuspicious(String text) {
boolean isLowercase = text.equals(text.toLowerCase());
boolean isUppercase = !isLowercase && text.equals(text.toUpperCase());
boolean isLowercase = text.equals(StringUtil.toLowerCase(text));
boolean isUppercase = !isLowercase && text.equals(StringUtil.toUpperCase(text));
return !isLowercase && !isUppercase || isLowercase && StringUtil.containsAnyChar(text, "-_");
}
}
Loading
Loading