-
Notifications
You must be signed in to change notification settings - Fork 0
Formatting java code with ebnf like grammar #26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Shopin-Igor
merged 29 commits into
main
from
formatting-java-code-with-ebnf-like-grammar
May 18, 2026
Merged
Changes from all commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
2ba94fb
При обращении к незарегистрированной вершине, теперь происходит её р…
d106e30
Добавил проверку на то, что RuleDef известен как DSL тип, на то, что …
6587b00
Теперь мы пишем правила, называя элементы в них, как в Java Parser, и…
aea3982
Добавлен простой тест DSL + код => отформатированный код, более сложн…
14ff3a5
Поправил, чтобы теперь с одним именем можно было писать несколько раз…
74c8b12
del old func require
303069a
На основе последней правки про разные типы правил с одним названием, …
fdd0b00
spec не бывает null, readProperty либо кидает ошибку, либо возвращает…
7a287c4
переменная property не бывает null, функция property либо кидает ошиб…
6732552
Добавил полноценное правило на форматирование, пока что не использует…
928ea6f
Добавил тесты из документации, <node*> и <node?> пока что не поддержи…
2b775ae
Вышла новая версия gradle
3dece05
Ввожу концепцию: если для вершины выбранно DSL правило и построены bi…
05c58d3
Реализация этой концепции
04d3824
Поправил тесты, теперь там нет хардкода, форматируется по общим правилам
ff0dc06
Добавил много тестов на форматирование от CompilationUnit до листьев AST
a008f2f
Обновил версию javaparser, до того, который поддерживает 25 java
e7f7875
если для <Statement> правила есть, но, например, конкретный whileStmt…
5520308
Добавил вывод для вершин без правил через PrettyPriner Java Parser + …
d5abed8
теперь тест в while, которого нет в правилах успешно проходит, код не…
95822a9
раньще был хардкод, в нём был прописан пробел при выводе
6c145e2
50 тестов на парсинг конструкций, которых нет в правилах
19300c6
Добавил тесты на проверку новвоведений (много конструкций, на которые…
812fc36
Удалил синтаксис для sql подобного типа правил, который уже не исполь…
cc162a6
Добавил пользовательскую инструкцию на то, как писать правила, когда …
370e583
Добавил возможность вынести в placeholder компоненты, которые не явля…
74432fc
Написал тесты на те ситуации, когда в правилах участвуют компоненты, …
5a04a5d
Добавил в гайд часть про то, как писать правила на не Node
c8fef30
Поправил опечатку
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,5 @@ | ||
| distributionBase=GRADLE_USER_HOME | ||
| distributionPath=wrapper/dists | ||
| distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-bin.zip | ||
| networkTimeout=10000 | ||
| validateDistributionUrl=true | ||
| distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip | ||
| zipStoreBase=GRADLE_USER_HOME | ||
| zipStorePath=wrapper/dists |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
10 changes: 10 additions & 0 deletions
10
src/main/java/org/example/ebnfFormatter/match/AppliedRule.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| package org.example.ebnfFormatter.match; | ||
|
|
||
| import org.example.ebnfFormatter.model.RuleDef; | ||
|
|
||
| public record AppliedRule( | ||
| String logicalName, | ||
| RuleDef rule, | ||
| Object sourceValue, | ||
| Bindings bindings | ||
| ) {} |
8 changes: 8 additions & 0 deletions
8
src/main/java/org/example/ebnfFormatter/match/AppliedRuleValue.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| package org.example.ebnfFormatter.match; | ||
|
|
||
| public record AppliedRuleValue(AppliedRule appliedRule) implements BoundValue { | ||
| @Override | ||
| public Object legacyValue() { | ||
| return appliedRule.sourceValue(); | ||
| } | ||
| } |
123 changes: 111 additions & 12 deletions
123
src/main/java/org/example/ebnfFormatter/match/Bindings.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,59 +1,158 @@ | ||
| package org.example.ebnfFormatter.match; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.LinkedHashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
| import java.util.Set; | ||
|
|
||
| public final class Bindings { | ||
|
|
||
| private final Map<String, Object> bindingsByName = new LinkedHashMap<>(); | ||
| private final Map<String, List<BoundValue>> bindingsByName = new LinkedHashMap<>(); | ||
|
|
||
| public boolean bind(String name, Object value) { | ||
| return bind(name, new RawValue(value)); | ||
| } | ||
|
|
||
| public boolean bind(String name, BoundValue value) { | ||
| if (!bindingsByName.containsKey(name)) { | ||
| bindingsByName.put(name, value); | ||
| bindingsByName.put(name, new ArrayList<>(List.of(value))); | ||
| return true; | ||
| } | ||
| return Objects.equals(bindingsByName.get(name), value); | ||
|
|
||
| List<BoundValue> existing = bindingsByName.get(name); | ||
| return existing.size() == 1 && Objects.equals(existing.getFirst(), value); | ||
| } | ||
|
|
||
| public boolean bindAll(String name, List<BoundValue> values) { | ||
| if (!bindingsByName.containsKey(name)) { | ||
| bindingsByName.put(name, new ArrayList<>(values)); | ||
| return true; | ||
| } | ||
|
|
||
| return Objects.equals(bindingsByName.get(name), values); | ||
| } | ||
|
|
||
| public void append(String name, BoundValue value) { | ||
| bindingsByName.computeIfAbsent(name, ignored -> new ArrayList<>()).add(value); | ||
| } | ||
|
|
||
| public void appendAll(Bindings other) { | ||
| for (Map.Entry<String, List<BoundValue>> entry : other.bindingsByName.entrySet()) { | ||
| bindingsByName | ||
| .computeIfAbsent(entry.getKey(), ignored -> new ArrayList<>()) | ||
| .addAll(entry.getValue()); | ||
| } | ||
| } | ||
|
|
||
| public Bindings copy() { | ||
| Bindings copy = new Bindings(); | ||
| copy.bindingsByName.putAll(this.bindingsByName); | ||
| for (Map.Entry<String, List<BoundValue>> entry : bindingsByName.entrySet()) { | ||
| copy.bindingsByName.put(entry.getKey(), new ArrayList<>(entry.getValue())); | ||
| } | ||
| return copy; | ||
| } | ||
|
|
||
| public void replaceWith(Bindings other) { | ||
| bindingsByName.clear(); | ||
| bindingsByName.putAll(other.bindingsByName); | ||
| for (Map.Entry<String, List<BoundValue>> entry : other.bindingsByName.entrySet()) { | ||
| bindingsByName.put(entry.getKey(), new ArrayList<>(entry.getValue())); | ||
| } | ||
| } | ||
|
|
||
| public Object getRequired(String name) { | ||
| if (!bindingsByName.containsKey(name)) { | ||
| List<BoundValue> values = findValuesInternal(name); | ||
| if (values == null) { | ||
| throw new IllegalArgumentException("No binding for name: " + name); | ||
| } | ||
| return bindingsByName.get(name); | ||
| return unwrapForLegacyUse(values); | ||
| } | ||
|
|
||
| public Object find(String name) { | ||
| return bindingsByName.get(name); | ||
| List<BoundValue> values = findValuesInternal(name); | ||
| if (values == null || values.isEmpty()) { | ||
| return null; | ||
| } | ||
| return unwrapForLegacyUse(values); | ||
| } | ||
|
|
||
| public List<BoundValue> getRequiredValues(String name) { | ||
| List<BoundValue> values = findValuesInternal(name); | ||
| if (values == null) { | ||
| throw new IllegalArgumentException("No binding for name: " + name); | ||
| } | ||
| return List.copyOf(values); | ||
| } | ||
|
|
||
| public List<BoundValue> findValues(String name) { | ||
| List<BoundValue> values = findValuesInternal(name); | ||
| if (values == null) { | ||
| return List.of(); | ||
| } | ||
| return List.copyOf(values); | ||
| } | ||
|
|
||
| public boolean hasBinding(String name) { | ||
| return bindingsByName.containsKey(name); | ||
| return findValuesInternal(name) != null; | ||
| } | ||
|
|
||
| public Set<String> getBindingNames() { | ||
| return Collections.unmodifiableSet(bindingsByName.keySet()); | ||
| } | ||
|
|
||
| public Map<String, Object> asUnmodifiableMap() { | ||
| return Collections.unmodifiableMap(bindingsByName); | ||
| public Map<String, List<BoundValue>> asUnmodifiableMap() { | ||
| Map<String, List<BoundValue>> copy = new LinkedHashMap<>(); | ||
| for (Map.Entry<String, List<BoundValue>> entry : bindingsByName.entrySet()) { | ||
| copy.put(entry.getKey(), List.copyOf(entry.getValue())); | ||
| } | ||
| return Collections.unmodifiableMap(copy); | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return bindingsByName.toString(); | ||
| } | ||
| } | ||
|
|
||
| private List<BoundValue> findValuesInternal(String name) { | ||
| List<BoundValue> exact = bindingsByName.get(name); | ||
| if (exact != null) { | ||
| return exact; | ||
| } | ||
|
|
||
| String normalized = stripQuantifierSuffix(name); | ||
| if (normalized.equals(name)) { | ||
| return null; | ||
| } | ||
| return bindingsByName.get(normalized); | ||
| } | ||
|
|
||
| private String stripQuantifierSuffix(String name) { | ||
| if (name == null || name.isEmpty()) { | ||
| return name; | ||
| } | ||
|
|
||
| char last = name.charAt(name.length() - 1); | ||
| return switch (last) { | ||
| case '?', '*', '+' -> name.substring(0, name.length() - 1); | ||
| default -> name; | ||
| }; | ||
| } | ||
|
|
||
| private Object unwrapForLegacyUse(List<BoundValue> values) { | ||
| if (values.isEmpty()) { | ||
| return null; | ||
| } | ||
|
|
||
| if (values.size() == 1) { | ||
| return values.getFirst().legacyValue(); | ||
| } | ||
|
|
||
| List<Object> legacyValues = new ArrayList<>(values.size()); | ||
| for (BoundValue value : values) { | ||
| legacyValues.add(value.legacyValue()); | ||
| } | ||
| return legacyValues; | ||
| } | ||
| } |
5 changes: 5 additions & 0 deletions
5
src/main/java/org/example/ebnfFormatter/match/BoundValue.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| package org.example.ebnfFormatter.match; | ||
|
|
||
| public sealed interface BoundValue permits RawValue, AppliedRuleValue { | ||
| Object legacyValue(); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: мне казалось, что это было удалено N PR-ов назад