• Stars
    star
    715
  • Rank 63,327 (Top 2 %)
  • Language
    Java
  • License
    Other
  • Created over 13 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Grammar files support & parser/PSI generation for IntelliJ IDEA

Grammar-Kit

Build Status GitHub license official project

An IntelliJ IDEA plugin for language plugin developers.
Adds BNF Grammars and JFlex files editing support, and a parser/PSI code generator.

Quick links: Latest dev build, Changelog, Tutorial, How-to

Note

Since 2022.3, Grammar-Kit plugin requires Java 17.

Open-source plugins built with Grammar-Kit:

General usage instructions

  1. Create grammar *.bnf file, see Grammar.bnf in the plugin code.
  2. Tune the grammar using Live Preview + Structure view (Ctrl-Alt-P / Cmd-Alt-P)
  3. Generate parser/ElementTypes/PSI classes (Ctrl-Shift-G / Cmd-Shift-G)
  4. Generate lexer *.flex file and then run JFlex generator (both via context menu)
  5. Implement ParserDefinition and add the corresponding registrations to the plugin.xml
  6. Mix-in resolve and other non-trivial functionality to PSI

Using with Gradle

Invoking the parser generator from an IDE as described above is the preferred way.
Otherwise use gradle-grammar-kit-plugin if the following limitations are not critical:

  • Method mixins are not supported (two-pass generation is not implemented)
  • Generic signatures and annotations may not be correct

Plugin features

Editor support

  • Refactoring: extract rule (Ctrl-Alt-M/Cmd-Alt-M)
  • Refactoring: introduce token (Ctrl-Alt-C/Cmd-Alt-C)
  • Editing: flip choice branches intention (via Alt-Enter)
  • Editing: Unwrap/remove expression (Ctrl-Shift-Del/Cmd-Shift-Del)
  • Navigation: quick grammar and flex file structure popup (Ctrl-F12/Cmd-F12)
  • Navigation: go to related file (parser and PSI) (Ctrl-Alt-Home/Cmd-Alt-Home)
  • Navigation: navigate to matched expressions (Ctrl-B/Cmd-B inside attribute pattern)
  • Highlighting: customizable colors (via Settings/Colors and Fonts)
  • Highlighting: pinned expression markers (tooltip shows pin value in charge)
  • Highlighting: a number of inspections, the list is available in Settings/Inspections
  • Documentation: rule documentation popup shows FIRST/FOLLOWS/PSI content (Ctrl-Q/Cmd-J)
  • Documentation: attribute documentation popup (Ctrl-Q/Cmd-J)
  • Live preview: open language live preview editor (Ctrl-Alt-P/Cmd-Alt-P)
  • Live preview: start/stop grammar evaluator highlighting (Ctrl-Alt-F7/Cmd-Alt-F7 in preview editor)
  • Generator: generate parser/PSI code (Ctrl-Shift-G/Cmd-Shift-G)
  • Generator: generate custom parserUtilClass class
  • Generator: generate *.flex - JFlex lexer definition
  • Generator: run JFlex generator on a *.flex file
  • Diagram: PSI tree diagram (UML plugin required)

Syntax overview

See Parsing Expression Grammar (PEG) for basic syntax. Use ::= for ← symbol. You can also use [ .. ] for optional sequences and { | | } for choices as these variants are popular in real-world grammars. Grammar-Kit source code is the main example of Grammar-Kit application. The grammar for BNF parser and PSI generation can be found here.

Here's how it may look like:

// Basic PEG BNF syntax

root_rule ::= rule_A rule_B rule_C rule_D                // sequence expression
rule_A ::= token | 'or_text' | "another_one"             // choice expression
rule_B ::= [ optional_token ] and_another_one?           // optional expression
rule_C ::= &required !forbidden                          // predicate expression
rule_D ::= { can_use_braces + (and_parens) * }           // grouping and repetition

// Grammar-Kit BNF syntax

{ generate=[psi="no"] }                                  // top-level global attributes
private left rule_with_modifier ::= '+'                  // rule modifiers
left rule_with_attributes ::= '?' {elementType=rule_D}   // rule attributes

private meta list ::= <<p>> (',' <<p>>) *                // meta rule with parameters
private list_usage ::= <<list rule_D>>                   // meta rule application

The basic syntax is extended with global attributes and rule attributes. Attributes are specified by the list of name=value pairs enclosed in braces. Rule attributes are placed right after the rule definition. Global attributes are placed on top or separated from a rule definition with a semicolon.

Generator generates a static method for each BNF expression as follows:

static boolean rule_name(..)               // rule top level expression
static boolean rule_name_0(..)             // rule sub-expression
...                                        // ...
static boolean rule_name_N1_N2_..._NX      // rule sub-sub-...-sub-expression

Naming a rule like rule_name_N1_N2_..._NX shall be avoided.

One can specify an attribute for several rules at once in a global attributes block:

{
  extends(".*_expr")=expr        // applies to all .*_expr rules
  pin(".*_list(?:_\d+)*")=1      // applies to all .*_list rules and their sub-expressions
}

Rule modifiers:

  1. private (PSI tree): skip node creation and let its child nodes be included in its parent.

  2. left (PSI tree): take an AST node on the left (previous sibling) and enclose it by becoming its parent.

  3. inner (PSI tree): take an AST node on the left (previous sibling) and inject itself into it by becoming its child.

  4. upper (PSI tree): take the parent node and replace it by adopting all its children.

  5. meta (parser): a parametrized rule; its parse function can take other parse functions as parameters.

  6. external (parser): a rule with a hand-written parse function; no parsing code is generated.

  7. fake (PSI classes): a rule for shaping the generated PSI classes; only PSI classes are generated.

Modifiers can be combined, inner should only be used together with left, private left is equivalent to private left inner, fake should not be combined with private.

By default, rules are public, i.e. non-private, non-fake, etc.

Meta rules & external expressions:

The external expression << ... >> is simply an inline variant of an external rule. It can also be used to specify a meta rule along with arguments.

For example:

meta comma_separated_list ::= <<param>> ( ',' <<param>> ) *
option_list ::= <<comma_separated_list (OPTION1 | OPTION2 | OPTION3)>>

External rule expression syntax is the same as a body of external expression:

 external manually_parsed_rule ::= methodName param1 param2 ...

External expressions and external rules interpret double- and single-quoted strings differently. Generally, anything that appears in an external expression after rule or method name is treated as a parameter and passed "as is" except single-quoted strings which are unquoted first. This helps to pass qualified enum constants, java expressions, etc.

Rule references in parameter list are implemented as GeneratedParserUtilBase.Parser instances.

Tokens:

Explicit tokens are declared via tokens global attribute, e.g. in token_name=token_value form. A token name is for the IElementType token constant, a token value is usually its string representation in single or double-quotes.

Tokens in grammar can be referenced by name or by value in single or double-quotes. It is recommended to use values where possible for better readability. Names can be used to resolve conflicts when there is an unquoted token value that also matches some rule.

Implicit tokens are tokens not specified via tokens attribute. Unquoted implicit tokens (aka keyword tokens) have names equals to their values. Quoted implicit tokens (aka text-matched tokens) are slow because they are matched by text and not by an IElementType constant returned by a lexer. Text-matched tokens can span more than one real token returned by the lexer.

Rules, tokens, and text-matched tokens have different colors.

Attributes for error recovery and reporting:

  • pin (value: a number or pattern) tunes the parser to handle incomplete matches. A sequence matches if its prefix up to a pinned item matches. On successfully reaching the pinned item the parser tries to match the rest items whether they match or not. Pin value indicates the desired item by either a number {pin=2} or pattern {pin="rule_B"}. By default, the pin is applied to the top sequence expression. Sub-expressions can be included using a target pattern: {pin(".*")=1} applies to all sub-sequences.

  • recoverWhile (value: predicate rule) matches any number of tokens after the rule matching completes with any result. This attribute helps the parser recover when an unmatched token sequence is encountered. See HOWTO section for more.

  • name (value: string) specifies a name for a rule to be used in error reports. For example, *name("_.expr")=expression changes expression error messages to "<expression> required" instead of a long list of tokens.

Generated parser structure:

The generator can split parser code into several classes for better support of large grammars.

In simple cases, a parser will consist just of several generated classes.

The actual error recovery and reporting code as well as the parser-based completion provider support code and the basic token matching code reside in a parserUtilClass class. It may be altered by specifying some other class that extends or mimics the original GeneratedParserUtilBase. There's no need to keep a copy of GeneratedParserUtilBase in a project, it is included in IntelliJ Platform since version 12.1.

The manual parsing code, i.e. external rules must be implemented the same way as generated, by a static method in the parserUtilClass class or any other class that will be imported via parserImports attribute like this:

{
  parserImports=["static org.sample.ManualParsing.*"]
}

Lexer and PSI:

IElementType constants generated by the parser generator have to be recognized and returned by the lexer. The JFlex-based lexer can be generated from a grammar that defines all the required tokens ( Generate JFlex Lexer menu).

Run JFlex Generator menu in a *.flex file calls JFlex to generate lexer java code. Keywords are picked right from usages while tokens like string, identifier and comment can be defined like this (from TUTORIAL):

{
  tokens=[
    ...
    comment='regexp://.*'
    number='regexp:\d+(\.\d*)?'
    id='regexp:\p{Alpha}\w*'
    string="regexp:('([^'\\]|\\.)*'|\"([^\"\\]|\\.)*\")"
    ...
  ]
  ...
}

While Live Preview mode supports full Java RegExp syntax and JFlex supports only a subset (see JFlex documentation) Grammar-Kit tries to perform some obvious conversions.

The lexer can be provided separately or one can use the generated *.flex file as a base.

Parser generator generates token types constants and PSI by default. This can be switched off via generateTokens and generatePSI global boolean attributes respectively.

elementType rule attribute allows mixing the generated code and some existing hand-made PSI.

More Repositories

1

kotlin

The Kotlin Programming Language.
Kotlin
48,745
star
2

intellij-community

IntelliJ IDEA Community Edition & IntelliJ Platform
Java
17,135
star
3

compose-multiplatform

Compose Multiplatform, a modern UI framework for Kotlin that makes building performant and beautiful user interfaces easy and enjoyable.
Kotlin
16,179
star
4

JetBrainsMono

JetBrains Mono – the free and open-source typeface for developers
Shell
10,765
star
5

Exposed

Kotlin SQL Framework
Kotlin
8,296
star
6

ideavim

IdeaVim – A Vim engine for JetBrains IDEs
Kotlin
7,980
star
7

kotlin-native

Kotlin/Native infrastructure
Kotlin
7,026
star
8

ring-ui

A collection of JetBrains Web UI components
TypeScript
3,595
star
9

intellij-platform-plugin-template

Template repository for creating plugins for IntelliJ Platform
Kotlin
3,048
star
10

kotlinconf-app

KotlinConf Schedule Application
Kotlin
2,967
star
11

skija

Java bindings for Skia
Java
2,628
star
12

create-react-kotlin-app

Create React apps using Kotlin with no build configuration
JavaScript
2,480
star
13

projector-docker

Run JetBrains IDEs remotely with Docker
Shell
2,235
star
14

intellij-plugins

Open-source plugins included in the distribution of IntelliJ IDEA Ultimate and other IDEs based on the IntelliJ Platform
Java
2,002
star
15

svg-sprite-loader

Webpack loader for creating SVG sprites.
JavaScript
1,998
star
16

skiko

Kotlin Multiplatform bindings to Skia
C++
1,825
star
17

compose-multiplatform-ios-android-template

Compose Multiplatform iOS+Android Application project template
Kotlin
1,600
star
18

lets-plot

Multiplatform plotting library based on the Grammar of Graphics
Kotlin
1,559
star
19

MPS

JetBrains Meta programming System
JetBrains MPS
1,527
star
20

kotlin-web-site

The Kotlin programming language website
JavaScript
1,474
star
21

intellij-platform-gradle-plugin

Gradle plugin for building plugins for IntelliJ-based IDEs
Kotlin
1,426
star
22

kotlin-wrappers

Kotlin wrappers for popular JavaScript libraries
Kotlin
1,339
star
23

phpstorm-stubs

PHP runtime & extensions header files for PhpStorm
PHP
1,317
star
24

JetBrainsRuntime

Runtime environment based on OpenJDK for running IntelliJ Platform-based products on Windows, macOS, and Linux
Java
1,312
star
25

idea-gitignore

.ignore support plugin for IntelliJ IDEA
Kotlin
1,290
star
26

projector-server

Server-side library for running Swing applications remotely
Kotlin
1,246
star
27

intellij-sdk-docs

IntelliJ SDK Platform Documentation
Markdown
1,212
star
28

resharper-unity

Unity support for both ReSharper and Rider
C#
1,209
star
29

intellij-scala

Scala plugin for IntelliJ IDEA
Scala
1,192
star
30

xodus

Transactional schema-less embedded database used by JetBrains YouTrack and JetBrains Hub.
Java
1,180
star
31

kotless

Kotlin Serverless Framework
Kotlin
1,147
star
32

intellij-sdk-code-samples

Mirror of the IntelliJ SDK Docs Code Samples
Java
1,074
star
33

amper

Amper - a project configuration and build tool with a focus on the user experience and the IDE support
Kotlin
995
star
34

js-graphql-intellij-plugin

GraphQL language support for WebStorm, IntelliJ IDEA and other IDEs based on the IntelliJ Platform.
Java
879
star
35

android

Android Plugin for IntelliJ IDEA. This repository is a subset of https://git.jetbrains.org/?p=idea/android.git cut according to GitHub file size limitations.
Kotlin
863
star
36

projector-installer

Install, configure and run JetBrains IDEs with Projector Server on Linux or in WSL
Python
808
star
37

projector-client

Common and client-related code for running Swing applications remotely
Kotlin
806
star
38

jewel

An implementation of the IntelliJ look and feels in Compose for Desktop
Kotlin
709
star
39

markdown

Markdown parser written in kotlin
Kotlin
691
star
40

Arend

The Arend Proof Assistant
Java
691
star
41

jediterm

Pure Java Terminal Emulator. Works with SSH and PTY.
Java
675
star
42

compose-multiplatform-template

Compose Multiplatform Application project template
Kotlin
623
star
43

lincheck

Framework for testing concurrent data structures
Kotlin
576
star
44

Nitra

Public Nitra repository
Nemerle
549
star
45

intellij-micropython

Plugin for MicroPython devices in PyCharm and IntelliJ
Python
506
star
46

compose-multiplatform-desktop-template

Compose Multiplatform Desktop Application project template
Kotlin
447
star
47

kotlin-playground

Self-contained component to embed in websites for running Kotlin code
JavaScript
440
star
48

lets-plot-kotlin

Grammar of Graphics for Kotlin
Kotlin
434
star
49

java-annotations

Annotations for JVM-based languages.
Kotlin
405
star
50

colorSchemeTool

Python
396
star
51

Qodana

πŸ“ Source repository of Qodana Help
389
star
52

phpstorm-attributes

PhpStorm specific attributes
PHP
388
star
53

godot-support

C#
385
star
54

rd

Reactive Distributed communication framework for .NET, Kotlin, C++. Inspired by Rider IDE.
C#
385
star
55

pty4j

Pty for Java
Java
354
star
56

Unity3dRider

Unity JetBrains Rider integration
348
star
57

resharper-fsharp

F# support in JetBrains Rider
F#
328
star
58

phpstorm-workshop

Code for the PhpStorm workshop
PHP
287
star
59

web-types

JSON standard for documenting web component libraries for IDEs, documentation generators and other tools
TypeScript
280
star
60

awesome-pycharm

A curated list of resources for learning and using PyCharm, a Python IDE from JetBrains
280
star
61

gradle-changelog-plugin

Plugin for parsing and managing the Changelog in a "keep a changelog" style.
Kotlin
266
star
62

youtrack-mobile

A iOS and Android client for YouTrack
TypeScript
265
star
63

meta-runner-power-pack

A set of Meta-runners for TeamCity
PowerShell
256
star
64

inspection-plugin

Gradle plugin to launch IDEA inspections
Kotlin
256
star
65

ideolog

Interactive viewer for '.log' files.
Kotlin
254
star
66

qodana-action

βš™οΈ Scan your Go, Java, Kotlin, PHP, Python, JavaScript, TypeScript, .NET projects at GitHub with Qodana. This repository contains Qodana for Azure, GitHub, CircleCI and Gradle
JavaScript
248
star
67

jcef

A simple framework for embedding Chromium-based browsers into Java-based applications.
Java
245
star
68

kotlin-compiler-server

Server for executing kotlin code
Kotlin
241
star
69

gradle-idea-ext-plugin

Plugin to store IJ settings in gradle script
Groovy
233
star
70

resharper-rider-samples

Simple interactive exercises to help learn ReSharper and Rider
C#
225
star
71

php-timeline

Notable events of PHP history
222
star
72

la-clojure

Clojure plugin for IntelliJ IDEA
Java
220
star
73

jdk8u_jdk

Java
212
star
74

pest-intellij

The official Pest Plugin for PhpStorm / IntelliJ IDEA
Kotlin
197
star
75

youtrack-workflows

YouTrack Custom Workflow Repository
JavaScript
194
star
76

psiviewer

PSI Viewer for IntelliJ IDEA plugin development
Java
184
star
77

intellij-plugin-verifier

Compatibility verification tool for IntelliJ Platform plugins
Kotlin
178
star
78

resharper-rider-plugin

https://www.jetbrains.com/help/resharper/sdk/
PowerShell
175
star
79

rider-efcore

Entity Framework Core UI plugin for JetBrains Rider
Kotlin
174
star
80

svg-mixer

Node.js toolset for generating & transforming SVG images and sprites in modern way
JavaScript
173
star
81

qodana-cli

πŸ”§ JetBrains Qodana’s official command line tool
Go
171
star
82

phpstorm-docker-images

Pre-configured Docker images used by PhpStorm team
Dockerfile
171
star
83

compose-for-web-demos

Historical repository of early Compose for Web effort.
170
star
84

kotlin-web-demo

Online mini-IDE for Kotlin
Kotlin
167
star
85

intellij-samples

Code that demonstrates various IntelliJ IDEA features
Java
167
star
86

jetbrains_guide

JetBrains Guides where Developer Advocacy and the community share ideas.
CSS
164
star
87

jdk8u_hotspot

C++
159
star
88

educational-plugin

Educational plugin to learn and teach programming languages such as Kotlin, Java, Python, JavaScript, and others right inside of JetBrains IntelliJ Platform based IDEs.
Kotlin
152
star
89

teamcity-messages

Python Unit Test Reporting to TeamCity
Python
139
star
90

lets-plot-skia

Skia frontend for Lets-Plot multiplatform plotting library.
Kotlin
137
star
91

ruby-type-inference

Dynamic definitions and types provider for ruby static analysis
Kotlin
137
star
92

YouTrackSharp

.NET Standard 2.0 Library to access YouTrack API.
C#
134
star
93

clion-remote

134
star
94

resharper-angularjs

ReSharper plugin for AngularJS support
JavaScript
134
star
95

UnrealLink

C++
132
star
96

golandtipsandtricks

This is an ever evolving repository for GoLand Tips&Tricks
Go
132
star
97

python-skeletons

The python-skeltons repo is deprecated: use PEP 484 and Typeshed instead
Python
132
star
98

phpstorm-phpstan-plugin

PHPStan plugin for PhpStorm
Java
131
star
99

clion-wsl

Shell
130
star
100

teamcity-docker-samples

TeamCity docker compose samples
Shell
128
star