Unvendor tree-sitter-dart

pull/892/head
Antonin Delpeuch 2025-10-04 12:29:47 +07:00 committed by Wilfred Hughes
parent c75d87ead7
commit 6fbd425b55
76 changed files with 16 additions and 238053 deletions

11
Cargo.lock generated

@ -281,6 +281,7 @@ dependencies = [
"tree-sitter-cmake", "tree-sitter-cmake",
"tree-sitter-cpp", "tree-sitter-cpp",
"tree-sitter-css", "tree-sitter-css",
"tree-sitter-dart-orchard",
"tree-sitter-elixir", "tree-sitter-elixir",
"tree-sitter-erlang", "tree-sitter-erlang",
"tree-sitter-fsharp", "tree-sitter-fsharp",
@ -1071,6 +1072,16 @@ dependencies = [
"tree-sitter-language", "tree-sitter-language",
] ]
[[package]]
name = "tree-sitter-dart-orchard"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "206d0062b36beab07b152aa9c02f5b4944453cd942ba01471df951b40292e9ad"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]] [[package]]
name = "tree-sitter-elixir" name = "tree-sitter-elixir"
version = "0.3.4" version = "0.3.4"

@ -82,6 +82,7 @@ tree-sitter-c-sharp = "0.23.1"
tree-sitter-cmake = "0.7.1" tree-sitter-cmake = "0.7.1"
tree-sitter-cpp = "0.23.4" tree-sitter-cpp = "0.23.4"
tree-sitter-css = "0.23.1" tree-sitter-css = "0.23.1"
tree-sitter-dart-orchard = "0.2.1"
tree-sitter-elixir = "0.3.4" tree-sitter-elixir = "0.3.4"
tree-sitter-erlang = "0.13.0" tree-sitter-erlang = "0.13.0"
tree-sitter-fsharp = "0.1.0" tree-sitter-fsharp = "0.1.0"

@ -82,11 +82,6 @@ fn main() {
src_dir: "vendored_parsers/tree-sitter-commonlisp-src", src_dir: "vendored_parsers/tree-sitter-commonlisp-src",
extra_files: vec![], extra_files: vec![],
}, },
TreeSitterParser {
name: "tree-sitter-dart",
src_dir: "vendored_parsers/tree-sitter-dart-src",
extra_files: vec!["scanner.c"],
},
TreeSitterParser { TreeSitterParser {
name: "tree-sitter-devicetree", name: "tree-sitter-devicetree",
src_dir: "vendored_parsers/tree-sitter-devicetree-src", src_dir: "vendored_parsers/tree-sitter-devicetree-src",

@ -17,7 +17,7 @@ with `difft --list-languages`.
| Clojure | [sogaiu/tree-sitter-clojure](https://github.com/sogaiu/tree-sitter-clojure) | | Clojure | [sogaiu/tree-sitter-clojure](https://github.com/sogaiu/tree-sitter-clojure) |
| CMake | [uyha/tree-sitter-cmake](https://github.com/uyha/tree-sitter-cmake) | | CMake | [uyha/tree-sitter-cmake](https://github.com/uyha/tree-sitter-cmake) |
| Common Lisp | [theHamsta/tree-sitter-commonlisp](https://github.com/theHamsta/tree-sitter-commonlisp) | | Common Lisp | [theHamsta/tree-sitter-commonlisp](https://github.com/theHamsta/tree-sitter-commonlisp) |
| Dart | [UserNobody14/tree-sitter-dart](https://github.com/UserNobody14/tree-sitter-dart) | | Dart | [grammar-orchard/tree-sitter-dart](https://codeberg.org/grammar-orchard/tree-sitter-dart-orchard) |
| Device Tree | [joelspadin/tree-sitter-devicetree](https://github.com/joelspadin/tree-sitter-devicetree) | | Device Tree | [joelspadin/tree-sitter-devicetree](https://github.com/joelspadin/tree-sitter-devicetree) |
| Elixir | [elixir-lang/tree-sitter-elixir](https://github.com/elixir-lang/tree-sitter-elixir) | | Elixir | [elixir-lang/tree-sitter-elixir](https://github.com/elixir-lang/tree-sitter-elixir) |
| Elm | [elm-tooling/tree-sitter-elm](https://github.com/elm-tooling/tree-sitter-elm) | | Elm | [elm-tooling/tree-sitter-elm](https://github.com/elm-tooling/tree-sitter-elm) |

@ -73,7 +73,6 @@ extern "C" {
fn tree_sitter_apex() -> ts::Language; fn tree_sitter_apex() -> ts::Language;
fn tree_sitter_clojure() -> ts::Language; fn tree_sitter_clojure() -> ts::Language;
fn tree_sitter_commonlisp() -> ts::Language; fn tree_sitter_commonlisp() -> ts::Language;
fn tree_sitter_dart() -> ts::Language;
fn tree_sitter_devicetree() -> ts::Language; fn tree_sitter_devicetree() -> ts::Language;
fn tree_sitter_elisp() -> ts::Language; fn tree_sitter_elisp() -> ts::Language;
fn tree_sitter_elm() -> ts::Language; fn tree_sitter_elm() -> ts::Language;
@ -276,14 +275,15 @@ pub(crate) fn from_language(language: guess::Language) -> TreeSitterConfig {
} }
} }
Dart => { Dart => {
let language = unsafe { tree_sitter_dart() }; let language_fn = tree_sitter_dart_orchard::LANGUAGE;
let language = tree_sitter::Language::new(language_fn);
TreeSitterConfig { TreeSitterConfig {
language: language.clone(), language: language.clone(),
atom_nodes: ["string_literal", "script_tag"].into_iter().collect(), atom_nodes: ["string_literal", "script_tag"].into_iter().collect(),
delimiter_tokens: vec![("{", "}"), ("(", ")"), ("[", "]"), ("<", ">")], delimiter_tokens: vec![("{", "}"), ("(", ")"), ("[", "]"), ("<", ">")],
highlight_query: ts::Query::new( highlight_query: ts::Query::new(
&language, &language,
include_str!("../../vendored_parsers/highlights/dart.scm"), tree_sitter_dart_orchard::HIGHLIGHTS_QUERY,
) )
.unwrap(), .unwrap(),
sub_languages: vec![], sub_languages: vec![],

@ -1 +0,0 @@
../tree-sitter-dart/queries/highlights.scm

@ -1 +0,0 @@
tree-sitter-dart/src

@ -1,20 +0,0 @@
node_modules
.node-version
build
*.log
/test.js
/examples/npm
package-lock.json
/parser.exp
/parser.lib
/parser.obj
/scanner.obj
/.idea/
.dart_tool
.packages
pubspec.lock
.antlr
*.so
*.dll
*.dylib
doc

@ -1,6 +0,0 @@
[submodule "tree-sitter"]
path = tree_sitter/tree-sitter
url = git@github.com:tree-sitter/tree-sitter
[submodule "tree_sitter/tree-sitter"]
path = tree_sitter/tree-sitter
url = git@github.com:tree-sitter/tree-sitter

@ -1,14 +0,0 @@
{
"[dart]": {
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.formatOnType": true,
"editor.rulers": [
80
],
"editor.codeActionsOnSave": {
"source.organizeImports": true,
"source.fixAll": true
}
}
}

@ -1,26 +0,0 @@
[package]
name = "tree-sitter-dart"
description = "dart grammar for the tree-sitter parsing library"
version = "0.0.1"
keywords = ["incremental", "parsing", "dart"]
categories = ["parsing", "text-editors"]
repository = "https://github.com/tree-sitter/tree-sitter-javascript"
edition = "2018"
license = "MIT"
build = "bindings/rust/build.rs"
include = [
"bindings/rust/*",
"grammar.js",
"queries/*",
"src/*",
]
[lib]
path = "bindings/rust/lib.rs"
[dependencies]
tree-sitter = "0.17"
[build-dependencies]
cc = "1.0"

File diff suppressed because it is too large Load Diff

@ -1,20 +0,0 @@
Copyright (c) 2020-2023 UserNobody14 and others
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -1,18 +0,0 @@
# tree-sitter-dart
This is a tree-sitter grammar written for the dart programming language. We attempt to adhere as closely as possible to the dart language spec. Initially it was started with a copy of the tree-sitter Java grammar which is why there may be a few relics included in here. For the sake of simplifying the syntax tree, many items were made inlined with tree-sitter's "underscore" method of writing rules.
# Getting Started
- Go to the project directory
- run `npm install` (first time)
- run `npm run build_init` (first time) `npm run build` (subsequent times)
- run `npm run test`
# To test a single highlight file
- run `tree-sitter highlight test/highlight/types.dart`
# To test a single test file
- run `tree-sitter test -f 'testcasefilter'`
- for example `tree-sitter test -f 'dart string literals'`
# To show the output of a parse for a sample file (for example while debugging highlight issues)
- run `tree-sitter parse path/to/file.dart`

@ -1,461 +0,0 @@
let tree;
(async () => {
const CAPTURE_REGEX = /@\s*([\w\._-]+)/g;
const COLORS_BY_INDEX = [
'blue',
'chocolate',
'darkblue',
'darkcyan',
'darkgreen',
'darkred',
'darkslategray',
'dimgray',
'green',
'indigo',
'navy',
'red',
'sienna',
];
const scriptURL = document.currentScript.getAttribute('src');
const codeInput = document.getElementById('code-input');
const languageSelect = document.getElementById('language-select');
const loggingCheckbox = document.getElementById('logging-checkbox');
const outputContainer = document.getElementById('output-container');
const outputContainerScroll = document.getElementById('output-container-scroll');
const playgroundContainer = document.getElementById('playground-container');
const queryCheckbox = document.getElementById('query-checkbox');
const queryContainer = document.getElementById('query-container');
const queryInput = document.getElementById('query-input');
const updateTimeSpan = document.getElementById('update-time');
const languagesByName = {};
loadState();
await TreeSitter.init();
const parser = new TreeSitter();
const codeEditor = CodeMirror.fromTextArea(codeInput, {
lineNumbers: true,
showCursorWhenSelecting: true
});
const queryEditor = CodeMirror.fromTextArea(queryInput, {
lineNumbers: true,
showCursorWhenSelecting: true
});
const cluster = new Clusterize({
rows: [],
noDataText: null,
contentElem: outputContainer,
scrollElem: outputContainerScroll
});
const renderTreeOnCodeChange = debounce(renderTree, 50);
const saveStateOnChange = debounce(saveState, 2000);
const runTreeQueryOnChange = debounce(runTreeQuery, 50);
let languageName = languageSelect.value;
let treeRows = null;
let treeRowHighlightedIndex = -1;
let parseCount = 0;
let isRendering = 0;
let query;
codeEditor.on('changes', handleCodeChange);
codeEditor.on('viewportChange', runTreeQueryOnChange);
codeEditor.on('cursorActivity', debounce(handleCursorMovement, 150));
queryEditor.on('changes', debounce(handleQueryChange, 150));
loggingCheckbox.addEventListener('change', handleLoggingChange);
queryCheckbox.addEventListener('change', handleQueryEnableChange);
languageSelect.addEventListener('change', handleLanguageChange);
outputContainer.addEventListener('click', handleTreeClick);
handleQueryEnableChange();
await handleLanguageChange()
playgroundContainer.style.visibility = 'visible';
async function handleLanguageChange() {
const newLanguageName = languageSelect.value;
if (!languagesByName[newLanguageName]) {
const url = `${LANGUAGE_BASE_URL}/tree-sitter-${newLanguageName}.wasm`
languageSelect.disabled = true;
try {
languagesByName[newLanguageName] = await TreeSitter.Language.load(url);
} catch (e) {
console.error(e);
languageSelect.value = languageName;
return
} finally {
languageSelect.disabled = false;
}
}
tree = null;
languageName = newLanguageName;
parser.setLanguage(languagesByName[newLanguageName]);
handleCodeChange();
handleQueryChange();
}
async function handleCodeChange(editor, changes) {
const newText = codeEditor.getValue() + '\n';
const edits = tree && changes && changes.map(treeEditForEditorChange);
const start = performance.now();
if (edits) {
for (const edit of edits) {
tree.edit(edit);
}
}
const newTree = parser.parse(newText, tree);
const duration = (performance.now() - start).toFixed(1);
updateTimeSpan.innerText = `${duration} ms`;
if (tree) tree.delete();
tree = newTree;
parseCount++;
renderTreeOnCodeChange();
runTreeQueryOnChange();
saveStateOnChange();
}
async function renderTree() {
isRendering++;
const cursor = tree.walk();
let currentRenderCount = parseCount;
let row = '';
let rows = [];
let finishedRow = false;
let visitedChildren = false;
let indentLevel = 0;
for (let i = 0;; i++) {
if (i > 0 && i % 10000 === 0) {
await new Promise(r => setTimeout(r, 0));
if (parseCount !== currentRenderCount) {
cursor.delete();
isRendering--;
return;
}
}
let displayName;
if (cursor.nodeIsMissing) {
displayName = `MISSING ${cursor.nodeType}`
} else if (cursor.nodeIsNamed) {
displayName = cursor.nodeType;
}
if (visitedChildren) {
if (displayName) {
finishedRow = true;
}
if (cursor.gotoNextSibling()) {
visitedChildren = false;
} else if (cursor.gotoParent()) {
visitedChildren = true;
indentLevel--;
} else {
break;
}
} else {
if (displayName) {
if (finishedRow) {
row += '</div>';
rows.push(row);
finishedRow = false;
}
const start = cursor.startPosition;
const end = cursor.endPosition;
const id = cursor.nodeId;
let fieldName = cursor.currentFieldName();
if (fieldName) {
fieldName += ': ';
} else {
fieldName = '';
}
row = `<div>${' '.repeat(indentLevel)}${fieldName}<a class='plain' href="#" data-id=${id} data-range="${start.row},${start.column},${end.row},${end.column}">${displayName}</a> [${start.row}, ${start.column}] - [${end.row}, ${end.column}])`;
finishedRow = true;
}
if (cursor.gotoFirstChild()) {
visitedChildren = false;
indentLevel++;
} else {
visitedChildren = true;
}
}
}
if (finishedRow) {
row += '</div>';
rows.push(row);
}
cursor.delete();
cluster.update(rows);
treeRows = rows;
isRendering--;
handleCursorMovement();
}
function runTreeQuery(_, startRow, endRow) {
if (endRow == null) {
const viewport = codeEditor.getViewport();
startRow = viewport.from;
endRow = viewport.to;
}
codeEditor.operation(() => {
const marks = codeEditor.getAllMarks();
marks.forEach(m => m.clear());
if (tree && query) {
const captures = query.captures(
tree.rootNode,
{row: startRow, column: 0},
{row: endRow, column: 0},
);
let lastNodeId;
for (const {name, node} of captures) {
if (node.id === lastNodeId) continue;
lastNodeId = node.id;
const {startPosition, endPosition} = node;
codeEditor.markText(
{line: startPosition.row, ch: startPosition.column},
{line: endPosition.row, ch: endPosition.column},
{
inclusiveLeft: true,
inclusiveRight: true,
css: `color: ${colorForCaptureName(name)}`
}
);
}
}
});
}
function handleQueryChange() {
if (query) {
query.delete();
query.deleted = true;
query = null;
}
queryEditor.operation(() => {
queryEditor.getAllMarks().forEach(m => m.clear());
if (!queryCheckbox.checked) return;
const queryText = queryEditor.getValue();
try {
query = parser.getLanguage().query(queryText);
let match;
let row = 0;
queryEditor.eachLine((line) => {
while (match = CAPTURE_REGEX.exec(line.text)) {
queryEditor.markText(
{line: row, ch: match.index},
{line: row, ch: match.index + match[0].length},
{
inclusiveLeft: true,
inclusiveRight: true,
css: `color: ${colorForCaptureName(match[1])}`
}
);
}
row++;
});
} catch (error) {
const startPosition = queryEditor.posFromIndex(error.index);
const endPosition = {
line: startPosition.line,
ch: startPosition.ch + (error.length || Infinity)
};
if (error.index === queryText.length) {
if (startPosition.ch > 0) {
startPosition.ch--;
} else if (startPosition.row > 0) {
startPosition.row--;
startPosition.column = Infinity;
}
}
queryEditor.markText(
startPosition,
endPosition,
{
className: 'query-error',
inclusiveLeft: true,
inclusiveRight: true,
attributes: {title: error.message}
}
);
}
});
runTreeQuery();
saveQueryState();
}
function handleCursorMovement() {
if (isRendering) return;
const selection = codeEditor.getDoc().listSelections()[0];
let start = {row: selection.anchor.line, column: selection.anchor.ch};
let end = {row: selection.head.line, column: selection.head.ch};
if (
start.row > end.row ||
(
start.row === end.row &&
start.column > end.column
)
) {
let swap = end;
end = start;
start = swap;
}
const node = tree.rootNode.namedDescendantForPosition(start, end);
if (treeRows) {
if (treeRowHighlightedIndex !== -1) {
const row = treeRows[treeRowHighlightedIndex];
if (row) treeRows[treeRowHighlightedIndex] = row.replace('highlighted', 'plain');
}
treeRowHighlightedIndex = treeRows.findIndex(row => row.includes(`data-id=${node.id}`));
if (treeRowHighlightedIndex !== -1) {
const row = treeRows[treeRowHighlightedIndex];
if (row) treeRows[treeRowHighlightedIndex] = row.replace('plain', 'highlighted');
}
cluster.update(treeRows);
const lineHeight = cluster.options.item_height;
const scrollTop = outputContainerScroll.scrollTop;
const containerHeight = outputContainerScroll.clientHeight;
const offset = treeRowHighlightedIndex * lineHeight;
if (scrollTop > offset - 20) {
$(outputContainerScroll).animate({scrollTop: offset - 20}, 150);
} else if (scrollTop < offset + lineHeight + 40 - containerHeight) {
$(outputContainerScroll).animate({scrollTop: offset - containerHeight + 40}, 150);
}
}
}
function handleTreeClick(event) {
if (event.target.tagName === 'A') {
event.preventDefault();
const [startRow, startColumn, endRow, endColumn] = event
.target
.dataset
.range
.split(',')
.map(n => parseInt(n));
codeEditor.focus();
codeEditor.setSelection(
{line: startRow, ch: startColumn},
{line: endRow, ch: endColumn}
);
}
}
function handleLoggingChange() {
if (loggingCheckbox.checked) {
parser.setLogger((message, lexing) => {
if (lexing) {
console.log(" ", message)
} else {
console.log(message)
}
});
} else {
parser.setLogger(null);
}
}
function handleQueryEnableChange() {
if (queryCheckbox.checked) {
queryContainer.style.visibility = '';
queryContainer.style.position = '';
} else {
queryContainer.style.visibility = 'hidden';
queryContainer.style.position = 'absolute';
}
handleQueryChange();
}
function treeEditForEditorChange(change) {
const oldLineCount = change.removed.length;
const newLineCount = change.text.length;
const lastLineLength = change.text[newLineCount - 1].length;
const startPosition = {row: change.from.line, column: change.from.ch};
const oldEndPosition = {row: change.to.line, column: change.to.ch};
const newEndPosition = {
row: startPosition.row + newLineCount - 1,
column: newLineCount === 1
? startPosition.column + lastLineLength
: lastLineLength
};
const startIndex = codeEditor.indexFromPos(change.from);
let newEndIndex = startIndex + newLineCount - 1;
let oldEndIndex = startIndex + oldLineCount - 1;
for (let i = 0; i < newLineCount; i++) newEndIndex += change.text[i].length;
for (let i = 0; i < oldLineCount; i++) oldEndIndex += change.removed[i].length;
return {
startIndex, oldEndIndex, newEndIndex,
startPosition, oldEndPosition, newEndPosition
};
}
function colorForCaptureName(capture) {
const id = query.captureNames.indexOf(capture);
return COLORS_BY_INDEX[id % COLORS_BY_INDEX.length];
}
function loadState() {
const language = localStorage.getItem("language");
const sourceCode = localStorage.getItem("sourceCode");
const query = localStorage.getItem("query");
const queryEnabled = localStorage.getItem("queryEnabled");
if (language != null && sourceCode != null && query != null) {
queryInput.value = query;
codeInput.value = sourceCode;
languageSelect.value = language;
queryCheckbox.checked = (queryEnabled === 'true');
}
}
function saveState() {
localStorage.setItem("language", languageSelect.value);
localStorage.setItem("sourceCode", codeEditor.getValue());
saveQueryState();
}
function saveQueryState() {
localStorage.setItem("queryEnabled", queryCheckbox.checked);
localStorage.setItem("query", queryEditor.getValue());
}
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
})();

File diff suppressed because one or more lines are too long

@ -1,19 +0,0 @@
{
"targets": [
{
"target_name": "tree_sitter_dart_binding",
"include_dirs": [
"<!(node -e \"require('nan')\")",
"src"
],
"sources": [
"src/parser.c",
"bindings/node/binding.cc",
"src/scanner.c"
],
"cflags_c": [
"-std=c99",
]
}
]
}

@ -1,28 +0,0 @@
#include "tree_sitter/parser.h"
#include <node.h>
#include "nan.h"
using namespace v8;
extern "C" TSLanguage * tree_sitter_dart();
namespace {
NAN_METHOD(New) {}
void Init(Local<Object> exports, Local<Object> module) {
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Language").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Local<Function> constructor = Nan::GetFunction(tpl).ToLocalChecked();
Local<Object> instance = constructor->NewInstance(Nan::GetCurrentContext()).ToLocalChecked();
Nan::SetInternalFieldPointer(instance, 0, tree_sitter_dart());
Nan::Set(instance, Nan::New("name").ToLocalChecked(), Nan::New("dart").ToLocalChecked());
Nan::Set(module, Nan::New("exports").ToLocalChecked(), instance);
}
NODE_MODULE(tree_sitter_dart_binding, Init)
} // namespace

@ -1,19 +0,0 @@
try {
module.exports = require("../../build/Release/tree_sitter_dart_binding");
} catch (error1) {
if (error1.code !== 'MODULE_NOT_FOUND') {
throw error1;
}
try {
module.exports = require("../../build/Debug/tree_sitter_dart_binding");
} catch (error2) {
if (error2.code !== 'MODULE_NOT_FOUND') {
throw error2;
}
throw error1
}
}
try {
module.exports.nodeTypeInfo = require("../../src/node-types.json");
} catch (_) {}

@ -1,40 +0,0 @@
fn main() {
let src_dir = std::path::Path::new("src");
let mut c_config = cc::Build::new();
c_config.include(&src_dir);
c_config
.flag_if_supported("-Wno-unused-parameter")
.flag_if_supported("-Wno-unused-but-set-variable")
.flag_if_supported("-Wno-trigraphs");
let parser_path = src_dir.join("parser.c");
c_config.file(&parser_path);
// If your language uses an external scanner written in C,
// then include this block of code:
/*
let scanner_path = src_dir.join("scanner.c");
c_config.file(&scanner_path);
println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap());
*/
c_config.compile("parser");
println!("cargo:rerun-if-changed={}", parser_path.to_str().unwrap());
// If your language uses an external scanner written in C++,
// then include this block of code:
/*
let mut cpp_config = cc::Build::new();
cpp_config.cpp(true);
cpp_config.include(&src_dir);
cpp_config
.flag_if_supported("-Wno-unused-parameter")
.flag_if_supported("-Wno-unused-but-set-variable");
let scanner_path = src_dir.join("scanner.cc");
cpp_config.file(&scanner_path);
cpp_config.compile("scanner");
println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap());
*/
}

@ -1,52 +0,0 @@
//! This crate provides dart language support for the [tree-sitter][] parsing library.
//!
//! Typically, you will use the [language][language func] function to add this language to a
//! tree-sitter [Parser][], and then use the parser to parse some code:
//!
//! ```
//! let code = "";
//! let mut parser = tree_sitter::Parser::new();
//! parser.set_language(tree_sitter_dart::language()).expect("Error loading dart grammar");
//! let tree = parser.parse(code, None).unwrap();
//! ```
//!
//! [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
//! [language func]: fn.language.html
//! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html
//! [tree-sitter]: https://tree-sitter.github.io/
use tree_sitter::Language;
extern "C" {
fn tree_sitter_dart() -> Language;
}
/// Get the tree-sitter [Language][] for this grammar.
///
/// [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html
pub fn language() -> Language {
unsafe { tree_sitter_dart() }
}
/// The content of the [`node-types.json`][] file for this grammar.
///
/// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers#static-node-types
pub const NODE_TYPES: &'static str = include_str!("../../src/node-types.json");
// Uncomment these to include any queries that this grammar contains
// pub const HIGHLIGHTS_QUERY: &'static str = include_str!("../../queries/highlights.scm");
// pub const INJECTIONS_QUERY: &'static str = include_str!("../../queries/injections.scm");
// pub const LOCALS_QUERY: &'static str = include_str!("../../queries/locals.scm");
// pub const TAGS_QUERY: &'static str = include_str!("../../queries/tags.scm");
#[cfg(test)]
mod tests {
#[test]
fn test_can_load_grammar() {
let mut parser = tree_sitter::Parser::new();
parser
.set_language(super::language())
.expect("Error loading dart language");
}
}

File diff suppressed because it is too large Load Diff

@ -1,13 +0,0 @@
try {
module.exports = require("./build/Release/tree_sitter_dart_binding");
} catch (error) {
try {
module.exports = require("./build/Debug/tree_sitter_dart_binding");
} catch (_) {
throw error
}
}
try {
module.exports.nodeTypeInfo = require("./src/node-types.json");
} catch (_) {}

@ -1,67 +0,0 @@
{
"name": "tree-sitter-dart",
"version": "1.0.0",
"description": "Dart grammar attempt for tree-sitter",
"main": "bindings/node",
"keywords": [
"tree-sitter",
"parser",
"dart"
],
"contributors": [
"Benjamin Sobel",
"Tim Whiting <tim.a.whiting@gmail.com>",
"Stephan Seitz <stephan.seitz@fau.de>",
"Martin Jambon <github@mjambon.com>",
"Kyosuke Takayama @ktakayama",
"Han Wang @hanwangio",
"@akinsho",
"@seb-bl"
],
"license": "ISC",
"dependencies": {
"nan": "^2.17.0"
},
"devDependencies": {
"node-gyp": "^9.3.1",
"npm-watch": "^0.11.0",
"tree-sitter-cli": "^0.20.8"
},
"watch": {
"test": {
"patterns": [
"corpus"
],
"extensions": "dart",
"quiet": true
},
"build-test": {
"patterns": [
"./"
],
"extensions": [
"js",
"scm",
"txt"
],
"quiet": true
}
},
"scripts": {
"build_init": "tree-sitter generate && node-gyp configure && node-gyp build",
"build": "tree-sitter generate && node-gyp build",
"test": "tree-sitter test",
"build-test": "tree-sitter generate && node-gyp build && tree-sitter test",
"watch-test": "npm-watch test",
"watch-grammar": "npm-watch build-test"
},
"tree-sitter": [
{
"scope": "source.dart",
"file-types": [
"dart"
],
"injection-regex": "dart"
}
]
}

@ -1,6 +0,0 @@
name: _internal
environment:
sdk: '>=3.0.0-0 <3.2.0'
dependencies:
path: ^1.8.3

@ -1,224 +0,0 @@
(dotted_identifier_list) @string
; Methods
; --------------------
;; TODO: does not work
;(function_type
;name: (identifier) @method)
(super) @function
; Annotations
; --------------------
(annotation
name: (identifier) @attribute)
(marker_annotation
name: (identifier) @attribute)
; Operators and Tokens
; --------------------
(template_substitution
"$" @punctuation.special
"{" @punctuation.special
"}" @punctuation.special
) @none
(template_substitution
"$" @punctuation.special
(identifier_dollar_escaped) @variable
) @none
(escape_sequence) @string.escape
[
"@"
"=>"
".."
"??"
"=="
"?"
":"
"&&"
"%"
"<"
">"
"="
">="
"<="
"||"
(increment_operator)
(is_operator)
(prefix_operator)
(equality_operator)
(additive_operator)
] @operator
[
"("
")"
"["
"]"
"{"
"}"
] @punctuation.bracket
; Delimiters
; --------------------
[
";"
"."
","
] @punctuation.delimiter
; Types
; --------------------
(class_definition
name: (identifier) @type)
(constructor_signature
name: (identifier) @type)
;; TODO: does not work
;(type_identifier
;(identifier) @type)
(scoped_identifier
scope: (identifier) @type)
(function_signature
name: (identifier) @method)
(getter_signature
(identifier) @method)
(setter_signature
name: (identifier) @method)
(enum_declaration
name: (identifier) @type)
(enum_constant
name: (identifier) @type)
(type_identifier) @type
(void_type) @type
((scoped_identifier
scope: (identifier) @type
name: (identifier) @type)
(#match? @type "^[a-zA-Z]"))
(type_identifier) @type
; Variables
; --------------------
; var keyword
(inferred_type) @keyword
(const_builtin) @constant.builtin
(final_builtin) @constant.builtin
((identifier) @type
(#match? @type "^_?[A-Z]"))
("Function" @type)
; properties
; TODO: add method/call_expression to grammar and
; distinguish method call from variable access
(unconditional_assignable_selector
(identifier) @property)
; assignments
(assignment_expression
left: (assignable_expression) @variable)
(this) @variable.builtin
; Parameters
; --------------------
(formal_parameter
name: (identifier) @parameter)
(named_argument
(label (identifier) @parameter))
; Literals
; --------------------
[
(hex_integer_literal)
(decimal_integer_literal)
(decimal_floating_point_literal)
; TODO: inaccessbile nodes
; (octal_integer_literal)
; (hex_floating_point_literal)
] @number
(symbol_literal) @symbol
(string_literal) @string
(true) @boolean
(false) @boolean
(null_literal) @constant.builtin
(documentation_comment) @comment
(comment) @comment
; Keywords
; --------------------
["import" "library" "export"] @include
; Reserved words (cannot be used as identifiers)
; TODO: "rethrow" @keyword
[
; "assert"
(case_builtin)
"extension"
"on"
"class"
"enum"
"extends"
"in"
"is"
"new"
"return"
"super"
"with"
] @keyword
; Built in identifiers:
; alone these are marked as keywords
[
"abstract"
"as"
"async"
"async*"
"yield"
"sync*"
"await"
"covariant"
"deferred"
"dynamic"
"external"
"factory"
"get"
"implements"
"interface"
"library"
"operator"
"mixin"
"part"
"set"
"show"
"static"
"typedef"
] @keyword
; when used as an identifier:
((identifier) @variable.builtin
(#vim-match? @variable.builtin "^(abstract|as|covariant|deferred|dynamic|export|external|factory|Function|get|implements|import|interface|library|operator|mixin|part|set|static|typedef)$"))
["if" "else" "switch" "default"] @conditional
[
"try"
"throw"
"catch"
"finally"
(break_statement)
] @exception
["do" "while" "continue" "for"] @repeat
; Error
(ERROR) @error

@ -1 +0,0 @@
(if_statement (block))

@ -1,28 +0,0 @@
#include "tree_sitter/parser.h"
#include <node.h>
#include "nan.h"
using namespace v8;
extern "C" TSLanguage * tree_sitter_dart();
namespace {
NAN_METHOD(New) {}
void Init(Local<Object> exports, Local<Object> module) {
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Language").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Local<Function> constructor = Nan::GetFunction(tpl).ToLocalChecked();
Local<Object> instance = constructor->NewInstance(Nan::GetCurrentContext()).ToLocalChecked();
Nan::SetInternalFieldPointer(instance, 0, tree_sitter_dart());
Nan::Set(instance, Nan::New("name").ToLocalChecked(), Nan::New("dart").ToLocalChecked());
Nan::Set(module, Nan::New("exports").ToLocalChecked(), instance);
}
NODE_MODULE(tree_sitter_dart_binding, Init)
} // namespace

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,130 +0,0 @@
#include <tree_sitter/parser.h>
#include <wctype.h>
enum TokenType {
TEMPLATE_CHARS_SINGLE,
TEMPLATE_CHARS_DOUBLE,
TEMPLATE_CHARS_SINGLE_SINGLE,
TEMPLATE_CHARS_DOUBLE_SINGLE,
TEMPLATE_CHARS_RAW_SLASH,
BLOCK_COMMENT,
DOCUMENTATION_BLOCK_COMMENT,
};
void *tree_sitter_dart_external_scanner_create() { return NULL; }
void tree_sitter_dart_external_scanner_destroy(void *p) {}
void tree_sitter_dart_external_scanner_reset(void *p) {}
unsigned tree_sitter_dart_external_scanner_serialize(void *p, char *buffer) { return 0; }
void tree_sitter_dart_external_scanner_deserialize(void *p, const char *b, unsigned n) {}
static void advance(TSLexer *lexer) { lexer->advance(lexer, false); }
static void skip(TSLexer *lexer) { lexer->advance(lexer, true); }
static bool scan_multiline_comments(TSLexer *lexer) {
bool documentation_comment = false;
advance(lexer);
if (lexer->lookahead != '*') return false;
advance(lexer);
if (lexer->lookahead == '*') documentation_comment = true;
bool after_star = false;
unsigned nesting_depth = 1;
for (;;) {
switch (lexer->lookahead) {
case '\0':
return false;
case '*':
advance(lexer);
after_star = true;
break;
case '/':
if (after_star) {
advance(lexer);
after_star = false;
nesting_depth--;
if (nesting_depth == 0) {
if (!documentation_comment) {
lexer->result_symbol = BLOCK_COMMENT;
} else {
lexer->result_symbol = DOCUMENTATION_BLOCK_COMMENT;
}
return true;
}
} else {
advance(lexer);
after_star = false;
if (lexer->lookahead == '*') {
nesting_depth++;
advance(lexer);
}
}
break;
default:
advance(lexer);
after_star = false;
break;
}
}
return false;
}
static bool scan_templates(TSLexer *lexer, const bool *valid_symbols) {
if(valid_symbols[TEMPLATE_CHARS_DOUBLE]) {
lexer->result_symbol = TEMPLATE_CHARS_DOUBLE;
} else if (valid_symbols[TEMPLATE_CHARS_SINGLE]) {
lexer->result_symbol = TEMPLATE_CHARS_SINGLE;
} else if (valid_symbols[TEMPLATE_CHARS_SINGLE_SINGLE]) {
lexer->result_symbol = TEMPLATE_CHARS_SINGLE_SINGLE;
} else {
lexer->result_symbol = TEMPLATE_CHARS_DOUBLE_SINGLE;
}
for (bool has_content = false;; has_content = true) {
lexer->mark_end(lexer);
switch (lexer->lookahead) {
case '\'':
case '"':
return has_content;
case '\n':
if (valid_symbols[TEMPLATE_CHARS_DOUBLE_SINGLE] || valid_symbols[TEMPLATE_CHARS_SINGLE_SINGLE]) return false;
advance(lexer);
break;
case '\0':
return false;
case '$':
return has_content;
case '\\':
if (valid_symbols[TEMPLATE_CHARS_RAW_SLASH]) {
lexer->result_symbol = TEMPLATE_CHARS_RAW_SLASH;
advance(lexer);
} else {
return has_content;
}
break;
default:
advance(lexer);
}
}
return true;
}
bool tree_sitter_dart_external_scanner_scan(void *payload, TSLexer *lexer,
const bool *valid_symbols) {
if (
valid_symbols[TEMPLATE_CHARS_DOUBLE] ||
valid_symbols[TEMPLATE_CHARS_SINGLE] ||
valid_symbols[TEMPLATE_CHARS_DOUBLE_SINGLE] ||
valid_symbols[TEMPLATE_CHARS_SINGLE_SINGLE]
) {
return scan_templates(lexer, valid_symbols);
}
while (iswspace(lexer->lookahead)) lexer->advance(lexer, true);
if (lexer->lookahead == '/') {
return scan_multiline_comments(lexer);
}
return false;
}

@ -1,224 +0,0 @@
#ifndef TREE_SITTER_PARSER_H_
#define TREE_SITTER_PARSER_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#define ts_builtin_sym_error ((TSSymbol)-1)
#define ts_builtin_sym_end 0
#define TREE_SITTER_SERIALIZATION_BUFFER_SIZE 1024
typedef uint16_t TSStateId;
#ifndef TREE_SITTER_API_H_
typedef uint16_t TSSymbol;
typedef uint16_t TSFieldId;
typedef struct TSLanguage TSLanguage;
#endif
typedef struct {
TSFieldId field_id;
uint8_t child_index;
bool inherited;
} TSFieldMapEntry;
typedef struct {
uint16_t index;
uint16_t length;
} TSFieldMapSlice;
typedef struct {
bool visible;
bool named;
bool supertype;
} TSSymbolMetadata;
typedef struct TSLexer TSLexer;
struct TSLexer {
int32_t lookahead;
TSSymbol result_symbol;
void (*advance)(TSLexer *, bool);
void (*mark_end)(TSLexer *);
uint32_t (*get_column)(TSLexer *);
bool (*is_at_included_range_start)(const TSLexer *);
bool (*eof)(const TSLexer *);
};
typedef enum {
TSParseActionTypeShift,
TSParseActionTypeReduce,
TSParseActionTypeAccept,
TSParseActionTypeRecover,
} TSParseActionType;
typedef union {
struct {
uint8_t type;
TSStateId state;
bool extra;
bool repetition;
} shift;
struct {
uint8_t type;
uint8_t child_count;
TSSymbol symbol;
int16_t dynamic_precedence;
uint16_t production_id;
} reduce;
uint8_t type;
} TSParseAction;
typedef struct {
uint16_t lex_state;
uint16_t external_lex_state;
} TSLexMode;
typedef union {
TSParseAction action;
struct {
uint8_t count;
bool reusable;
} entry;
} TSParseActionEntry;
struct TSLanguage {
uint32_t version;
uint32_t symbol_count;
uint32_t alias_count;
uint32_t token_count;
uint32_t external_token_count;
uint32_t state_count;
uint32_t large_state_count;
uint32_t production_id_count;
uint32_t field_count;
uint16_t max_alias_sequence_length;
const uint16_t *parse_table;
const uint16_t *small_parse_table;
const uint32_t *small_parse_table_map;
const TSParseActionEntry *parse_actions;
const char * const *symbol_names;
const char * const *field_names;
const TSFieldMapSlice *field_map_slices;
const TSFieldMapEntry *field_map_entries;
const TSSymbolMetadata *symbol_metadata;
const TSSymbol *public_symbol_map;
const uint16_t *alias_map;
const TSSymbol *alias_sequences;
const TSLexMode *lex_modes;
bool (*lex_fn)(TSLexer *, TSStateId);
bool (*keyword_lex_fn)(TSLexer *, TSStateId);
TSSymbol keyword_capture_token;
struct {
const bool *states;
const TSSymbol *symbol_map;
void *(*create)(void);
void (*destroy)(void *);
bool (*scan)(void *, TSLexer *, const bool *symbol_whitelist);
unsigned (*serialize)(void *, char *);
void (*deserialize)(void *, const char *, unsigned);
} external_scanner;
const TSStateId *primary_state_ids;
};
/*
* Lexer Macros
*/
#define START_LEXER() \
bool result = false; \
bool skip = false; \
bool eof = false; \
int32_t lookahead; \
goto start; \
next_state: \
lexer->advance(lexer, skip); \
start: \
skip = false; \
lookahead = lexer->lookahead;
#define ADVANCE(state_value) \
{ \
state = state_value; \
goto next_state; \
}
#define SKIP(state_value) \
{ \
skip = true; \
state = state_value; \
goto next_state; \
}
#define ACCEPT_TOKEN(symbol_value) \
result = true; \
lexer->result_symbol = symbol_value; \
lexer->mark_end(lexer);
#define END_STATE() return result;
/*
* Parse Table Macros
*/
#define SMALL_STATE(id) id - LARGE_STATE_COUNT
#define STATE(id) id
#define ACTIONS(id) id
#define SHIFT(state_value) \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.state = state_value \
} \
}}
#define SHIFT_REPEAT(state_value) \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.state = state_value, \
.repetition = true \
} \
}}
#define SHIFT_EXTRA() \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.extra = true \
} \
}}
#define REDUCE(symbol_val, child_count_val, ...) \
{{ \
.reduce = { \
.type = TSParseActionTypeReduce, \
.symbol = symbol_val, \
.child_count = child_count_val, \
__VA_ARGS__ \
}, \
}}
#define RECOVER() \
{{ \
.type = TSParseActionTypeRecover \
}}
#define ACCEPT_INPUT() \
{{ \
.type = TSParseActionTypeAccept \
}}
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_PARSER_H_

@ -1,729 +0,0 @@
===================================================
Weird file
===================================================
d
---------------
(ERROR (ERROR (identifier)))
=====================================
more tests
======================================
typedef RpcPeerConnectionFunction = Future<vms.VmService> Function(
Uri uri, {
required Duration timeout,
});
---
(program
(type_alias
(type_identifier)
(function_type (type_identifier)
(type_arguments (type_identifier) (type_identifier))
(parameter_type_list
(normal_parameter_type
(typed_identifier
(type_identifier) (identifier)
)
)
(optional_parameter_types
(named_parameter_types
(typed_identifier (type_identifier) (identifier))))))))
=======================================
more tests2
=======================================
bool? _boolAttribute(
String resourceId,
String name,
Map<String, Object?> attributes,
String attributeName,
) {
final Object? value = attributes[attributeName];
if (value == null) {
return null;
}
if (value != 'true' && value != 'false') {
throw L10nException(
'The "$attributeName" value of the "$name" placeholder in message $resourceId '
'must be a boolean value.',
);
}
return value == 'true';
}
---
(program (function_signature (type_identifier) (nullable_type) (identifier)
(formal_parameter_list
(formal_parameter
(type_identifier) (identifier)) (formal_parameter (type_identifier) (identifier))
(formal_parameter
(type_identifier) (type_arguments (type_identifier) (type_identifier) (nullable_type))
(identifier))
(formal_parameter (type_identifier) (identifier)))
)
(function_body (block (local_variable_declaration
(initialized_variable_definition (final_builtin) (type_identifier) (nullable_type) (identifier)
(identifier) (selector (unconditional_assignable_selector (index_selector (identifier))))))
(if_statement (equality_expression (identifier) (equality_operator)
(null_literal)) (block (return_statement (null_literal))))
(if_statement (logical_and_expression
(equality_expression (identifier) (equality_operator) (string_literal))
(logical_and_operator)
(equality_expression (identifier) (equality_operator) (string_literal)))
(block (expression_statement (throw_expression (identifier)
(selector (argument_part (arguments (argument (string_literal
(template_substitution (identifier_dollar_escaped))
(template_substitution (identifier_dollar_escaped))
(template_substitution (identifier_dollar_escaped)))))))))))
(return_statement (equality_expression (identifier) (equality_operator) (string_literal))))))
===========================================
more tests 2
===========================================
/// A doctor validator for both Intellij and Android Studio.
abstract class IntelliJValidator extends DoctorValidator {
IntelliJValidator(super.title, this.installPath, {
required FileSystem fileSystem,
required UserMessages userMessages,
}) : _fileSystem = fileSystem,
_userMessages = userMessages;
final String installPath;
final FileSystem _fileSystem;
final UserMessages _userMessages;
String get version;
String? get pluginsPath;
static const Map<String, String> _idToTitle = <String, String>{
_ultimateEditionId: _ultimateEditionTitle,
_communityEditionId: _communityEditionTitle,
};
}
---
(program
(documentation_comment)
(class_definition (abstract) (identifier) (superclass (type_identifier))
(class_body (declaration (constructor_signature (identifier)
(formal_parameter_list
(formal_parameter (super_formal_parameter (super) (identifier)))
(formal_parameter (constructor_param (this) (identifier)))
(optional_formal_parameters (formal_parameter (type_identifier) (identifier))
(formal_parameter (type_identifier) (identifier)))))
(initializers (initializer_list_entry (field_initializer (identifier) (identifier)))
(initializer_list_entry (field_initializer (identifier) (identifier)))))
(declaration (final_builtin) (type_identifier) (initialized_identifier_list
(initialized_identifier (identifier)))) (declaration (final_builtin) (type_identifier)
(initialized_identifier_list (initialized_identifier (identifier))))
(declaration (final_builtin) (type_identifier)
(initialized_identifier_list (initialized_identifier (identifier))))
(declaration (getter_signature (type_identifier) (identifier)))
(declaration (getter_signature (type_identifier) (nullable_type) (identifier)))
(declaration (const_builtin) (type_identifier) (type_arguments (type_identifier)
(type_identifier)) (static_final_declaration_list (static_final_declaration (identifier)
(set_or_map_literal (type_arguments (type_identifier) (type_identifier))
(pair (identifier) (identifier)) (pair (identifier) (identifier)))))))))
==============================================
more tests 3
==============================================
class _RecompileRequest extends _CompilationRequest {
_RecompileRequest(
super.completer,
this.mainUri,
this.invalidatedFiles,
this.outputPath,
this.packageConfig,
this.suppressErrors,
{this.additionalSource}
);
Uri mainUri;
List<Uri>? invalidatedFiles;
String outputPath;
PackageConfig packageConfig;
bool suppressErrors;
final String? additionalSource;
@override
Future<CompilerOutput?> _run(DefaultResidentCompiler compiler) async =>
compiler._recompile(this);
}
---
(program
(class_definition (identifier)
(superclass (type_identifier))
(class_body (declaration
(constructor_signature (identifier)
(formal_parameter_list
(formal_parameter (super_formal_parameter (super) (identifier)))
(formal_parameter (constructor_param (this) (identifier)))
(formal_parameter (constructor_param (this) (identifier)))
(formal_parameter (constructor_param (this) (identifier)))
(formal_parameter (constructor_param (this) (identifier)))
(formal_parameter (constructor_param (this) (identifier)))
(optional_formal_parameters
(formal_parameter (constructor_param (this) (identifier)))))))
(declaration (type_identifier)
(initialized_identifier_list (initialized_identifier (identifier))))
(declaration (type_identifier) (type_arguments (type_identifier)) (nullable_type)
(initialized_identifier_list (initialized_identifier (identifier))))
(declaration (type_identifier) (initialized_identifier_list
(initialized_identifier (identifier)))) (declaration (type_identifier)
(initialized_identifier_list (initialized_identifier (identifier))))
(declaration (type_identifier) (initialized_identifier_list
(initialized_identifier (identifier))))
(declaration (final_builtin) (type_identifier) (nullable_type)
(initialized_identifier_list (initialized_identifier (identifier))))
(marker_annotation (identifier)) (method_signature
(function_signature (type_identifier) (type_arguments (type_identifier) (nullable_type))
(identifier) (formal_parameter_list (formal_parameter (type_identifier)
(identifier))))) (function_body (identifier) (selector
(unconditional_assignable_selector (identifier)))
(selector (argument_part (arguments (argument (this)))))))))
===============================
more tests 4
===============================
bool debugAssertIsValid() {
assert(
textColor != null
&& style != null
&& margin != null
&& _position != null
&& _position.isFinite
&& _opacity != null
&& _opacity >= 0.0
&& _opacity <= 1.0,
);
return true;
}
---
(program
(function_signature (type_identifier) (identifier) (formal_parameter_list))
(function_body (block (assert_statement
(assertion
(assertion_arguments (logical_and_expression
(equality_expression (identifier) (equality_operator) (null_literal))
(logical_and_operator)
(logical_and_expression
(equality_expression (identifier) (equality_operator) (null_literal))
(logical_and_operator)
(logical_and_expression (equality_expression (identifier) (equality_operator) (null_literal))
(logical_and_operator)
(logical_and_expression (equality_expression (identifier) (equality_operator) (null_literal))
(logical_and_operator)
(logical_and_expression (identifier) (selector (unconditional_assignable_selector (identifier)))
(logical_and_operator)
(logical_and_expression (equality_expression (identifier) (equality_operator) (null_literal))
(logical_and_operator)
(logical_and_expression
(relational_expression (identifier) (relational_operator)
(decimal_floating_point_literal))
(logical_and_operator)
(relational_expression (identifier) (relational_operator) (decimal_floating_point_literal)
)
)
)
)
)
)
)
))
)
) (return_statement (true)))))
===================================
more tests 5
===================================
main(){
var textTheme = TextTheme(error: '');
}
---
(program (function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(local_variable_declaration
(initialized_variable_definition
(inferred_type)
(identifier)
(identifier)
(selector
(argument_part
(arguments
(named_argument
(label
(identifier))
(string_literal))))))))))
===================================
more tests 6
===================================
void _layout(ConstraintType constraints) {
@pragma('vm:notify-debugger-on-exception')
void layoutCallback() {
Widget built;
try {
built = (widget as ConstrainedLayoutBuilder<ConstraintType>).builder(this, constraints);
debugWidgetBuilderValue(widget, built);
} catch (e, stack) {
built = ErrorWidget.builder(
_debugReportException(
informationCollector: () => <DiagnosticsNode>[
if (kDebugMode)
DiagnosticsDebugCreator(DebugCreator(this)),
],
),
);
}
}
owner!.buildScope(this, layoutCallback);
}
---
(program (function_signature (void_type) (identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier))))
(function_body
(block
(local_function_declaration (annotation (identifier)
(arguments (argument (string_literal))))
(lambda_expression
(function_signature (void_type) (identifier) (formal_parameter_list))
(function_body (block (local_variable_declaration
(initialized_variable_definition (type_identifier) (identifier)))
(try_statement
(block
(expression_statement
(assignment_expression (assignable_expression (identifier))
(parenthesized_expression
(type_cast_expression (identifier)
(type_cast (as_operator) (type_identifier) (type_arguments (type_identifier)))))
(selector (unconditional_assignable_selector (identifier)))
(selector (argument_part (arguments (argument (this)) (argument (identifier)))))))
(expression_statement
(identifier) (selector
(argument_part (arguments (argument (identifier)) (argument (identifier)))))))
(catch_clause (catch_parameters (identifier) (identifier)))
(block
(expression_statement (assignment_expression (assignable_expression (identifier)) (identifier)
(selector (unconditional_assignable_selector (identifier)))
(selector (argument_part (arguments (argument (identifier)
(selector (argument_part (arguments (named_argument (label (identifier))
(function_expression (formal_parameter_list) (function_expression_body
(list_literal (type_arguments (type_identifier))
(if_element (identifier) (identifier)
(selector (argument_part (arguments (argument (identifier)
(selector (argument_part (arguments (argument (this)))))))))))))))))))))))))))))
(expression_statement (identifier) (selector)
(selector (unconditional_assignable_selector (identifier)))
(selector (argument_part (arguments (argument (this)) (argument (identifier)))))))))
===================================
more tests 7
===================================
void _layout(ConstraintType constraints) {
@pragma('vm:notify-debugger-on-exception')
void layoutCallback() {
Widget built;
}
}
---
(program (function_signature (void_type) (identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier))))
(function_body (block (local_function_declaration (annotation (identifier)
(arguments (argument (string_literal))))
(lambda_expression
(function_signature (void_type) (identifier) (formal_parameter_list))
(function_body
(block (local_variable_declaration
(initialized_variable_definition (type_identifier) (identifier))))))))))
===================================
more tests 8
===================================
void _layout(ConstraintType constraints) {
@pragma('vm:notify-debugger-on-exception')
void layoutCallback() {
Widget built;
}
owner!.buildScope(this, layoutCallback);
}
---
(program (function_signature (void_type) (identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier))))
(function_body (block (local_function_declaration (annotation (identifier)
(arguments (argument (string_literal))))
(lambda_expression (function_signature (void_type) (identifier) (formal_parameter_list))
(function_body
(block
(local_variable_declaration
(initialized_variable_definition (type_identifier) (identifier)))))))
(expression_statement (identifier) (selector) (selector
(unconditional_assignable_selector (identifier)))
(selector (argument_part (arguments (argument (this)) (argument (identifier)))))))))
====================================
cascade selector
====================================
main() {
layer
?..link = link
..showWhenUnlinked = showWhenUnlinked
..linkedOffset = effectiveLinkedOffset
..unlinkedOffset = offset;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(identifier)
(cascade_section
(cascade_selector
(identifier))
(identifier))
(cascade_section
(cascade_selector
(identifier))
(identifier))
(cascade_section
(cascade_selector
(identifier))
(identifier))
(cascade_section
(cascade_selector
(identifier))
(identifier))))))
====================================
cascade selector 2
====================================
main() {
layer
..link = link
..showWhenUnlinked = showWhenUnlinked
..linkedOffset = effectiveLinkedOffset
..unlinkedOffset = offset;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(identifier)
(cascade_section
(cascade_selector
(identifier))
(identifier))
(cascade_section
(cascade_selector
(identifier))
(identifier))
(cascade_section
(cascade_selector
(identifier))
(identifier))
(cascade_section
(cascade_selector
(identifier))
(identifier))))))
====================================
comment selector 1
====================================
// C C* *=node removed next pass
//
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Stack(),
));
---
(program
(comment)
(comment)
(function_signature
(type_identifier)
(ERROR
(identifier))
(identifier)
(formal_parameter_list
(formal_parameter
(identifier)
(formal_parameter_list
(ERROR
(formal_parameter
(identifier)))
(formal_parameter
(type_identifier)
(type_identifier)
(ERROR
(identifier))
(identifier)
(formal_parameter_list)))))))
====================================
comment overselected 2
====================================
// }
//
class Placeholder {
Placeholder(this.resourceId, this.name, Map<String, Object?> attributes)
: assert(resourceId != null),
assert(name != null),
example = _stringAttribute(resourceId, name, attributes, 'example'),
type = _stringAttribute(resourceId, name, attributes, 'type') ?? 'Object';
final String resourceId;
}
---
(program (comment) (comment) (class_definition (identifier)
(class_body (declaration (constructor_signature (identifier) (formal_parameter_list
(formal_parameter (constructor_param (this) (identifier))) (formal_parameter (constructor_param (this) (identifier)))
(formal_parameter (type_identifier) (type_arguments (type_identifier) (type_identifier) (nullable_type) ) (identifier)))) (initializers
(initializer_list_entry (assertion (assertion_arguments (equality_expression (identifier) (equality_operator) (null_literal)))))
(initializer_list_entry (assertion (assertion_arguments (equality_expression (identifier) (equality_operator) (null_literal)))))
(initializer_list_entry (field_initializer (identifier) (identifier) (selector (argument_part (arguments (argument (identifier))
(argument (identifier)) (argument (identifier)) (argument (string_literal)))))))
(initializer_list_entry (field_initializer (identifier)
(if_null_expression (identifier) (selector
(argument_part
(arguments
(argument (identifier))
(argument (identifier))
(argument (identifier))
(argument (string_literal)))))
(string_literal))))))
(declaration (final_builtin) (type_identifier)
(initialized_identifier_list (initialized_identifier (identifier)))))))
================================================
static late final 1
================================================
class TestRoot extends StatefulWidget {
const TestRoot({ super.key });
static late final TestRootState state;
@override
State<TestRoot> createState() => TestRootState();
}
---
(program
(class_definition (identifier) (superclass (type_identifier))
(class_body
(declaration
(constant_constructor_signature (const_builtin) (identifier)
(formal_parameter_list (optional_formal_parameters
(formal_parameter (super_formal_parameter (super) (identifier)))))))
(declaration (final_builtin) (type_identifier)
(initialized_identifier_list (initialized_identifier (identifier))))
(marker_annotation (identifier))
(method_signature
(function_signature (type_identifier)
(type_arguments (type_identifier)) (identifier) (formal_parameter_list)))
(function_body (identifier) (selector (argument_part (arguments)))))))
================================================
static late final 2
================================================
class TestRoot extends StatefulWidget {
static late final TestRootState state;
}
---
(program (class_definition (identifier) (superclass (type_identifier))
(class_body (declaration (final_builtin) (type_identifier)
(initialized_identifier_list (initialized_identifier (identifier)))))))
===================
Error
===================
Offset getOffsetForCaret() {
switch (caretMetrics) {
case _EmptyLineCaretMetrics(:final double lineVerticalOffset):
final double paintOffsetAlignment = _computePaintOffsetFraction(textAlign, textDirection!);
// The full width is not (width - caretPrototype.width)
final double dx = paintOffsetAlignment == 0 ? 0 : paintOffsetAlignment * width;
return Offset(dx, lineVerticalOffset);
case _LineCaretMetrics(writingDirection: TextDirection.ltr, :final Offset offset):
rawOffset = offset;
case _LineCaretMetrics(writingDirection: TextDirection.rtl, :final Offset offset):
rawOffset = Offset(offset.dx - caretPrototype.width, offset.dy);
}
}
---
(program
(function_signature
(type_identifier)
(identifier)
(formal_parameter_list))
(function_body
(block
(switch_statement
(parenthesized_expression
(identifier))
(switch_block
(switch_statement_case
(case_builtin)
(object_pattern
(type_identifier)
(variable_pattern
(final_builtin)
(type_identifier)
(identifier)))
(local_variable_declaration
(initialized_variable_definition
(final_builtin)
(type_identifier)
(identifier)
(identifier)
(selector
(argument_part
(arguments
(argument
(identifier))
(argument
(identifier)
(selector)))))))
(comment)
(local_variable_declaration
(initialized_variable_definition
(final_builtin)
(type_identifier)
(identifier)
(conditional_expression
(equality_expression
(identifier)
(equality_operator)
(decimal_integer_literal))
(decimal_integer_literal)
(multiplicative_expression
(identifier)
(multiplicative_operator)
(identifier)))))
(return_statement
(identifier)
(selector
(argument_part
(arguments
(argument
(identifier))
(argument
(identifier)))))))
(switch_statement_case
(case_builtin)
(object_pattern
(type_identifier)
(identifier)
(constant_pattern
(qualified
(type_identifier)
(identifier)))
(variable_pattern
(final_builtin)
(type_identifier)
(identifier)))
(expression_statement
(assignment_expression
(assignable_expression
(identifier))
(identifier))))
(switch_statement_case
(case_builtin)
(object_pattern
(type_identifier)
(identifier)
(constant_pattern
(qualified
(type_identifier)
(identifier)))
(variable_pattern
(final_builtin)
(type_identifier)
(identifier)))
(expression_statement
(assignment_expression
(assignable_expression
(identifier))
(identifier)
(selector
(argument_part
(arguments
(argument
(additive_expression
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(additive_operator)
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))))
(argument
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))))))))))))))

@ -1,93 +0,0 @@
=============
Basic Classes
=============
class Hello {}
base class Base {}
interface class Interface {}
final class Final {}
sealed class Sealed {}
abstract class Abstract {}
---
(program
(class_definition
(identifier)
(class_body))
(class_definition
(base)
(identifier)
(class_body))
(class_definition
(interface)
(identifier)
(class_body))
(class_definition
(identifier)
(class_body))
(class_definition
(sealed)
(identifier)
(class_body))
(class_definition
(abstract)
(identifier)
(class_body)))
=============
Combo Classes
=============
abstract base class AbstractBase {}
abstract interface class AbstractInterface {}
abstract final class AbstractFinal {}
abstract mixin class AbstractMixin {}
abstract base mixin class AbstractBaseMixin {}
---
(program
(class_definition
(abstract)
(base)
(identifier)
(class_body))
(class_definition
(abstract)
(interface)
(identifier)
(class_body))
(class_definition
(abstract)
(identifier)
(class_body))
(class_definition
(abstract)
(mixin)
(identifier)
(class_body))
(class_definition
(abstract)
(base)
(mixin)
(identifier)
(class_body)))
=============
Mixins
=============
mixin Mixin {}
base mixin BaseMixin {}
---
(program
(mixin_declaration
(mixin)
(identifier)
(class_body))
(mixin_declaration
(base)
(mixin)
(identifier)
(class_body)))

@ -1,127 +0,0 @@
====
comment
====
// This is a comment
// comment with a link made in https://github.com/flutter/flutter/pull/48547
// Changes made in https://github.com/flutter/flutter/pull/48547
/* This is also a comment */
/* this comment /* // /** ends here: */
---
(program (comment) (comment) (comment) (comment) (comment))
======================
comments and literals
======================
final x = 123;
// comment
---
(program
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(decimal_integer_literal)))
(comment))
======================
documentation comment
======================
/// * [defaultSchedulingStrategy], the default [SchedulingStrategy] for [SchedulerBinding.schedulingStrategy].
---
(program (documentation_comment))
======================
documentation comment 1
======================
/**
* Is [:true:] if this comment is a documentation comment.
*
* That is, that the comment is either enclosed in [: /** ... */ :] or starts
* with [: /// :].
*/
---
(program (documentation_comment))
======================
documentation comment 2
======================
/**
* Is [:true:] if this comment is a documentation comment.
*
* That is, that the comment is either enclosed in [: /** ... */ :] or starts
*/
---
(program (documentation_comment))
======================
fake documentation comment
======================
/*
* Is [:true:] if this comment is a documentation comment.
*
* That is, that the comment is either enclosed in /* var ... */ var or starts
*/
---
(program (comment))
======================
documentation comment 3
======================
/**
* Is this comment is a documentation comment.
*
* That is, that the comment i
*/
---
(program (documentation_comment))
======================
regular comment 2
======================
/*
Nested comment /* ... */ bbbbbbbbbbbb
*/
---
(program (comment))
======================
regular comment 3
======================
/*/* ... */*/
---
(program (comment))

@ -1,348 +0,0 @@
=========================================
dart string literals
=========================================
get a => "";
get a => "\"";
get a => "This' is a string $mystring";
get a => '''This" is a
string ${mystring}''';
get a => 'Also a string';
---
(program
(getter_signature (identifier)) (function_body (string_literal))
(getter_signature (identifier)) (function_body (string_literal (escape_sequence)))
(getter_signature (identifier)) (function_body (string_literal (template_substitution (identifier_dollar_escaped))))
(getter_signature (identifier)) (function_body (string_literal (template_substitution (identifier))))
(getter_signature (identifier)) (function_body (string_literal)))
=========================================
dart string literals 2
=========================================
get a => "";
get a => "\"";
get a => """This' is a string $mystring""";
get a => '''This" is a $
string mystring''';
get a => '''Also a string''';
---
(program
(getter_signature (identifier)) (function_body (string_literal))
(getter_signature (identifier)) (function_body (string_literal (escape_sequence)))
(getter_signature (identifier)) (function_body (string_literal (template_substitution (identifier_dollar_escaped))))
(getter_signature (identifier)) (function_body (string_literal))
(getter_signature (identifier)) (function_body (string_literal)))
=========================================
dart string literals raw
=========================================
get a => "";
get a => r"\";
get a => """This' is a string $mystring""";
get a => '''This" is a $
string mystring''';
get a => r'''Also a string''';
---
(program
(getter_signature (identifier)) (function_body (string_literal))
(getter_signature (identifier)) (function_body (string_literal))
(getter_signature (identifier)) (function_body (string_literal (template_substitution (identifier_dollar_escaped))))
(getter_signature (identifier)) (function_body (string_literal))
(getter_signature (identifier)) (function_body (string_literal)))
==================================================
dart identifier name r (used to conflict/error with raw string literal)
==================================================
String hello(r) => 'hello';
---
(program
(function_signature (type_identifier) (identifier)
(formal_parameter_list (formal_parameter (identifier)))) (function_body (string_literal)))
==================================================
dart set literals
==================================================
class A {
int b() {
var c = {vala};
var c = {vala: 'g'};
}
}
---
(program
(class_definition
name: (identifier)
body: (class_body
(method_signature (function_signature
(type_identifier)
name: (identifier)
(formal_parameter_list)))
(function_body (block
(local_variable_declaration
(initialized_variable_definition
(inferred_type)
name: (identifier)
value: (set_or_map_literal (identifier))
))
(local_variable_declaration
(initialized_variable_definition
(inferred_type)
name: (identifier)
value: (set_or_map_literal (pair key: (identifier) value: (string_literal)))
)
))
))))
==================================================
embedded control flow for collections
==================================================
class A {
int b() {
var c = {if (z) vala};
var c = {vala: 'g'};
}
}
---
(program
(class_definition
name: (identifier)
body: (class_body
(method_signature (function_signature
(type_identifier)
name: (identifier)
(formal_parameter_list)))
(function_body (block
(local_variable_declaration
(initialized_variable_definition
(inferred_type)
name: (identifier)
value: (set_or_map_literal (if_element
(identifier)
consequence: (identifier)
))
)
)
(local_variable_declaration
(initialized_variable_definition
(inferred_type)
name: (identifier)
value: (set_or_map_literal (pair key: (identifier) value: (string_literal)))
)
))
)
)))
===================
Positional Parameters
===================
class Beyonce {
void calculateAnswer(double wingSpan, int numberOfEngines,
[double length, double grossTons]) {
//do the calculation here
}
}
---
(program
(class_definition
(identifier)
(class_body
(method_signature (function_signature
(void_type)
(identifier)
(formal_parameter_list
(formal_parameter (type_identifier) (identifier))
(formal_parameter (type_identifier) (identifier))
(optional_formal_parameters
(formal_parameter (type_identifier) (identifier))
(formal_parameter (type_identifier) (identifier))))))
(function_body (block (comment))))))
==================================================
collection trailing commas
==================================================
final map = {"hello": "world",};
final set = {"hello", "world"};
---
(program
(final_builtin)
(static_final_declaration_list (static_final_declaration (identifier)
(set_or_map_literal (pair (string_literal) (string_literal)))))
(final_builtin)
(static_final_declaration_list (static_final_declaration (identifier)
(set_or_map_literal (string_literal) (string_literal)))))
==================================================
collection literal type parameters
==================================================
final dynamic opts = <dynamic, dynamic>{
'transports': ['websocket'],
'forceNew': true,
};
---
(program (final_builtin) (type_identifier) (static_final_declaration_list (static_final_declaration (identifier)
(set_or_map_literal (type_arguments (type_identifier) (type_identifier)) (pair (string_literal)
(list_literal (string_literal))) (pair (string_literal) (true))))))
==================================================
extensions on integer literals
==================================================
void main() {
await Future.delayed(10.milliseconds, () {});
}
---
(program
(function_signature (void_type) (identifier) (formal_parameter_list))
(function_body (block (expression_statement (unary_expression
(await_expression (identifier) (selector (unconditional_assignable_selector (identifier))) (selector (argument_part
(arguments (argument (decimal_integer_literal) (selector (unconditional_assignable_selector (identifier))))
(argument (function_expression (formal_parameter_list) (function_expression_body (block)))))))))))))
==================================================
part directive
==================================================
part 'hello.dart';
---
(program (part_directive (uri (string_literal))))
==================================================
part of directive
==================================================
part of 'hello.dart';
---
(program (part_of_directive (uri (string_literal))))
==================================================
extension methods
==================================================
extension Hello on String {
String get hello => 'hello';
}
---
(program
(extension_declaration (identifier) (type_identifier) (extension_body
(method_signature (getter_signature (type_identifier) (identifier))) (function_body (string_literal)))))
==================================================
library directive
==================================================
library myLibrary;
---
(program (library_name (dotted_identifier_list (identifier))))
==================================================
scoped library directive
==================================================
library myLibrary.a.cool.library;
---
(program (library_name (dotted_identifier_list (identifier) (identifier) (identifier) (identifier))))
==================================================
redirecting factories
==================================================
@freezed
abstract class MyDataClass implements _$MyDataClass {
const factory MyDataClass.initialize({@Default(false) bool debug}) = _MyDataClassInitialize;
factory MyDataClass.debug() => MyDataClass.initialize(debug: true);
}
---
(program
(class_definition
(marker_annotation (identifier))
(abstract) (identifier) (interfaces (type_identifier))
(class_body
(declaration (redirecting_factory_constructor_signature (const_builtin) (identifier) (identifier) (formal_parameter_list
(optional_formal_parameters (formal_parameter
(annotation (identifier) (arguments (argument (false)))) (type_identifier) (identifier)))) (type_identifier)))
(method_signature (factory_constructor_signature (identifier) (identifier) (formal_parameter_list)))
(function_body (identifier) (selector (unconditional_assignable_selector (identifier)))
(selector (argument_part (arguments (named_argument (label (identifier)) (true)))))))))
======================================
setter expressions
======================================
class MyClass {
set editing(bool value) {
_editing = value;
}
}
---
(program (class_definition (identifier)
(class_body (method_signature
(setter_signature (identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier)))))
(function_body (block (expression_statement (assignment_expression (assignable_expression (identifier)) (identifier))))))))
======================================
Basic selector
======================================
void main() {
f(a.b);
}
---
(program
(function_signature (void_type) (identifier) (formal_parameter_list))
(function_body (block
(expression_statement
(identifier)
(selector (argument_part
(arguments
(argument
(identifier)
(selector (unconditional_assignable_selector (identifier)))))))))))

@ -1,698 +0,0 @@
===============
local variable
===============
class A {
int b() {
int c = 5;
}
}
---
(program
(class_definition
name: (identifier)
body: (class_body
(method_signature (function_signature
(type_identifier)
name: (identifier)
(formal_parameter_list))
)
(function_body (block
(local_variable_declaration (initialized_variable_definition
(type_identifier)
name: (identifier)
value: (decimal_integer_literal))))))))
===============================
single type import declaration
===============================
import 'package:dektor/catalog.dart';
---
(program (import_or_export (library_import (import_specification (configurable_uri (uri (string_literal)))))))
===========================
type_import_on_declaraction
===========================
import 'package:dektor/catalog.dart';
---
(program (import_or_export (library_import (import_specification (configurable_uri (uri (string_literal)))))))
=================================
single static import declaration
=================================
import 'package:dektor/catalog.dart';
---
(program (import_or_export (library_import (import_specification (configurable_uri (uri (string_literal)))))))
===================================
static import on demand declaration
===================================
import 'package:dektor/catalog.dart';
---
(program (import_or_export (library_import (import_specification (configurable_uri (uri (string_literal)))))))
=================
class declaration
=================
class Point {
}
---
(program
(class_definition
(identifier)
(class_body)))
=====================================================================
class declaration involving public, private, abstract and superclass
=====================================================================
class Point {
}
class Point {
}
abstract class ColoredPoint extends Point {
}
---
(program
(class_definition (identifier) (class_body))
(class_definition (identifier) (class_body))
(class_definition (abstract) (identifier) (superclass (type_identifier)) (class_body)))
==================================
class declaration with implements
==================================
class Dog implements ISpeak {
}
---
(program
(class_definition
(identifier)
(interfaces (type_identifier)) (class_body)))
============================
class declaration with body
============================
class Point {
var x;
var s = 'g';
void bar() {
x = 2;
}
}
---
(program
(class_definition
(identifier)
(class_body
(declaration
(inferred_type)
(initialized_identifier_list (initialized_identifier (identifier))))
(declaration
(inferred_type)
(initialized_identifier_list
(initialized_identifier
(identifier)
(string_literal))))
(method_signature (function_signature
(void_type)
(identifier)
(formal_parameter_list)))
(function_body
(block
(expression_statement
(assignment_expression (assignable_expression (identifier)) (decimal_integer_literal))))))))
===================
method declaration
===================
class Beyonce {
void calculateAnswer(double wingSpan, int numberOfEngines,
double length, double grossTons) {
//do the calculation here
}
}
---
(program
(class_definition
(identifier)
(class_body
(method_signature (function_signature
(void_type)
(identifier)
(formal_parameter_list
(formal_parameter (type_identifier) (identifier))
(formal_parameter (type_identifier) (identifier))
(formal_parameter (type_identifier) (identifier))
(formal_parameter (type_identifier) (identifier))))
)
(function_body
(block (comment))))))
========================
constructor declaration
========================
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
Point.json() {
this(0, 0);
}
Point.json(this.x, this.y);
}
---
(program
(class_definition
name: (identifier)
body: (class_body
(declaration
(type_identifier)
(initialized_identifier_list
(initialized_identifier (identifier))
(initialized_identifier (identifier))
)
)
(method_signature (constructor_signature
name: (identifier)
parameters: (formal_parameter_list
(formal_parameter
(type_identifier)
name: (identifier))
(formal_parameter
(type_identifier)
name: (identifier)))))
(function_body
(block (expression_statement (assignment_expression
left: (assignable_expression
(this)
(unconditional_assignable_selector (identifier))
)
right: (identifier))
)
(expression_statement (assignment_expression
left: (assignable_expression
(this)
(unconditional_assignable_selector (identifier))
)
right: (identifier))
)
))
(method_signature (constructor_signature
name: (identifier)
name: (identifier)
parameters: (formal_parameter_list)))
(function_body
(block
(expression_statement
(this)
(selector
(argument_part
(arguments
(argument (decimal_integer_literal))
(argument (decimal_integer_literal))
)
)
)
)
)
)
(declaration
(constructor_signature
name: (identifier)
name: (identifier)
parameters: (formal_parameter_list
(formal_parameter (constructor_param (this) (identifier)))
(formal_parameter (constructor_param (this) (identifier)))
)
)
)
)
)
)
======================
object instantiation
======================
class Point {
double Foo() {
new BufferedWriter();
}
}
---
(program
(class_definition
(identifier)
(class_body
(method_signature (function_signature
(type_identifier)
(identifier)
(formal_parameter_list))
)
(function_body (block
(expression_statement
(new_expression
(type_identifier)
(arguments)))
)))))
=====================
variable declaration
=====================
class JayZ {
void Beyonce() {
int blue_ivy_carter;
}
}
---
(program
(class_definition
(identifier)
(class_body
(method_signature (function_signature
(void_type)
(identifier)
(formal_parameter_list)))
(function_body
(block
(local_variable_declaration (initialized_variable_definition
(type_identifier)
(identifier))))))))
=================
enum declaration
=================
enum HandSign {
SCISSOR, PAPER, STONE
}
---
(program
(enum_declaration
name: (identifier)
body: (enum_body
(enum_constant name: (identifier))
(enum_constant name: (identifier))
(enum_constant name: (identifier)))))
=================
variable inferred type declaration
=================
var x = 0;
---
(program (inferred_type)
(initialized_identifier_list (initialized_identifier (identifier) (decimal_integer_literal))))
=================
top level annotated declaration
=================
@annotation
final y = 0;
---
(program
(marker_annotation (identifier))
(final_builtin)
(static_final_declaration_list (static_final_declaration (identifier) (decimal_integer_literal))))
=================
static final top level declaration
=================
final y = 1.0;
final double y1 = 1.0;
const z = "100";
const String z1 = "100";
---
(program
(final_builtin)
(static_final_declaration_list (static_final_declaration (identifier) (decimal_floating_point_literal)))
(final_builtin)
(type_identifier) (static_final_declaration_list (static_final_declaration (identifier) (decimal_floating_point_literal)))
(const_builtin)
(static_final_declaration_list (static_final_declaration (identifier) (string_literal)))
(const_builtin)
(type_identifier) (static_final_declaration_list (static_final_declaration (identifier) (string_literal))))
=================
identifier with dollar signs
=================
final $y$ = 0;
---
(program
(final_builtin)
(static_final_declaration_list (static_final_declaration (identifier) (decimal_integer_literal))))
=================
typedefs
=================
typedef CreateCallback = void Function(String);
typedef void EndCallback(String endValue);
typedef Future<String> Handler(String method, Map<String, String> parameters);
typedef MyFunction<T> = T Function();
typedef DismissMethod = Future<void> Function(WidgetTester tester, Finder finder, {@required AxisDirection gestureDirection});
---
(program
(type_alias (type_identifier)
(function_type
(void_type)
(parameter_type_list (normal_parameter_type (type_identifier)))))
(type_alias
(void_type)
(type_identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier))))
(type_alias
(type_identifier) (type_arguments (type_identifier))
(type_identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier)) (formal_parameter (type_identifier) (type_arguments (type_identifier) (type_identifier)) (identifier))))
(type_alias
(type_identifier) (type_parameters (type_parameter (type_identifier)))
(function_type (type_identifier) (parameter_type_list)))
(type_alias
(type_identifier)
(function_type (type_identifier) (type_arguments (void_type))
(parameter_type_list (normal_parameter_type (typed_identifier (type_identifier) (identifier))) (normal_parameter_type (typed_identifier (type_identifier) (identifier)))
(optional_parameter_types (named_parameter_types (marker_annotation (identifier)) (typed_identifier (type_identifier) (identifier))))))))
=================
script tag
=================
#! /usr/bin/env dshell
import 'package:dshell/dshell.dart';
---
(program
(script_tag)
(import_or_export (library_import (import_specification (configurable_uri (uri (string_literal)))))))
================================================================
non final and final declarations
================================================================
List<String> animations = ['1', '2', '3', '4', 'Default'];
final String assetFile = "assets/myasset.flr";
class MyClass {
}
---
(program
(type_identifier) (type_arguments (type_identifier))
(initialized_identifier_list (initialized_identifier (identifier) (list_literal (string_literal) (string_literal) (string_literal) (string_literal) (string_literal))))
(final_builtin)
(type_identifier) (static_final_declaration_list (static_final_declaration (identifier) (string_literal)))
(class_definition (identifier) (class_body)))
==================================
Nullable Function Parameter
==================================
void callback(Future<void> Function(String?) handler) {
}
---
(program
(function_signature (void_type) (identifier)
(formal_parameter_list
(formal_parameter
(function_type
(type_identifier)
(type_arguments (void_type))
(parameter_type_list (normal_parameter_type (type_identifier) (nullable_type)))) (identifier))))
(function_body (block)))
==================================
Type with Library Prefix
==================================
const my.MyType newMyType = my.MyType();
---
(program
(const_builtin)
(type_identifier)
(type_identifier)
(static_final_declaration_list
(static_final_declaration
(identifier)
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(selector
(argument_part
(arguments))))))
==================================
Type with Library Prefix Plus Final
==================================
final my.MyType newMyType = my.MyType();
main() {
final my.myType newMyType = ggg;
}
---
(program
(final_builtin)
(type_identifier)
(type_identifier)
(static_final_declaration_list
(static_final_declaration
(identifier)
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(selector
(argument_part
(arguments)))))
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(local_variable_declaration
(initialized_variable_definition
(final_builtin)
(type_identifier)
(type_identifier)
(identifier)
(identifier))))))
==================================
Null function argument
==================================
void _invoke(void callback()?, Zone? zone) {
}
---
(program
(function_signature (void_type) (identifier)
(formal_parameter_list
(formal_parameter (void_type) (identifier) (formal_parameter_list) (nullable_type))
(formal_parameter (type_identifier) (nullable_type) (identifier))))
(function_body (block)))
==================================
Get and set methods (not keyword)
==================================
// Interesting issue of conflict between dart grammar itself and actual value of elements?
String get(String hello) => 'A string $hello';
class MyClass {
void set(String name, Object value) {}
}
---
(program
(comment)
(function_signature (type_identifier) (identifier) (formal_parameter_list (formal_parameter (type_identifier) (identifier))))
(function_body (string_literal (template_substitution (identifier_dollar_escaped))))
(class_definition (identifier)
(class_body
(method_signature
(function_signature (void_type) (identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier)) (formal_parameter (type_identifier) (identifier)))))
(function_body (block)))))
==================================
Get and set methods (functional?)
==================================
String get myGetterName => 'A string hello';
class MyClass {
void set myValue(String name, Object value) {}
}
---
(program
(getter_signature (type_identifier) (identifier))
(function_body (string_literal))
(class_definition (identifier)
(class_body
(method_signature
(setter_signature (void_type) (identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier))
(formal_parameter (type_identifier) (identifier)))))
(function_body (block)))))
======================================
Get and set identifiers (ERROR)
======================================
class Tree {
Set toSet() {
Set set = Set();
set._count = _count;
set._root = _root;
return set;
}
}
---
(program
(class_definition
(identifier)
(class_body
(method_signature
(function_signature
(type_identifier)
(identifier)
(formal_parameter_list)))
(function_body
(block
(ERROR
(function_signature
(type_identifier)
(identifier)
(ERROR
(identifier))
(formal_parameter_list))
(identifier)
(identifier)
(identifier)
(identifier))
(return_statement
(identifier)))))))
==================================
void types
==================================
class MyClass {
void mySet(String name, Object value) {}
}
---
(program
(class_definition (identifier)
(class_body
(method_signature
(function_signature (void_type) (identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier))
(formal_parameter (type_identifier) (identifier)))))
(function_body (block)))))
==================================
external factories
==================================
class LinkedHashMap {
external factory LinkedHashMap();
external factory LinkedHashMap.identity();
}
---
(program
(class_definition (identifier)
(class_body
(declaration (factory_constructor_signature (identifier) (formal_parameter_list)))
(declaration (factory_constructor_signature (identifier) (identifier) (formal_parameter_list))))))

@ -1,94 +0,0 @@
===============
Enhanced Enums
===============
enum LogPriority with LogPriorityMixin implements Comparable<LogPriority> {
warning(2, "Warning"),
log.unknown("Log"),
;
LogPriority(this.priority, this.prefix);
LogPriority.unknown(String prefix) : this(-1, prefix);
final int priority;
int compareTo(Log other) => priority - other.priority;
}
---
(program
(enum_declaration
(identifier)
(mixins
(type_identifier))
(interfaces
(type_identifier)
(type_arguments
(type_identifier)))
(enum_body
(enum_constant
(identifier)
(argument_part
(arguments
(argument
(decimal_integer_literal))
(argument
(string_literal)))))
(enum_constant
(identifier)
(identifier)
(arguments
(argument
(string_literal))))
(declaration
(constructor_signature
(identifier)
(formal_parameter_list
(formal_parameter
(constructor_param
(this)
(identifier)))
(formal_parameter
(constructor_param
(this)
(identifier))))))
(declaration
(constructor_signature
(identifier)
(identifier)
(formal_parameter_list
(formal_parameter
(type_identifier)
(identifier))))
(redirection
(this)
(arguments
(argument
(unary_expression
(prefix_operator
(minus_operator))
(decimal_integer_literal)))
(argument
(identifier)))))
(declaration
(final_builtin)
(type_identifier)
(initialized_identifier_list
(initialized_identifier
(identifier))))
(method_signature
(function_signature
(type_identifier)
(identifier)
(formal_parameter_list
(formal_parameter
(type_identifier)
(identifier)))))
(function_body
(additive_expression
(identifier)
(additive_operator)
(identifier)
(selector
(unconditional_assignable_selector
(identifier))))))))

@ -1,18 +0,0 @@
============
Regression
============
final a = StateProvider<T12345678> // Complete expression is: final a = StateProvider<T1234567>();
// Yes this is an error, because it is a partial definition (no semicolon)
---
(ERROR
(final_builtin)
(identifier)
(type_identifier)
(type_arguments
(type_identifier))
(comment)
(comment))

@ -1,909 +0,0 @@
==================================
standalone assignment expression
==================================
main() {
x = 3;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(assignment_expression
(assignable_expression
(identifier))
(decimal_integer_literal))))))
==================================
standalone binary expression
==================================
main() {
a > b;
a < b;
a == b;
a >= b;
a <= b;
a != b;
a && b;
a || b;
a & b;
a | b;
a ^ b;
a % b;
a << b;
a >> b;
a >>> b;
3 + 2;
3 - 2;
3 * 2;
9 / 3;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(relational_expression
(identifier)
(relational_operator)
(identifier)))
(expression_statement
(relational_expression
(identifier)
(relational_operator)
(identifier)))
(expression_statement
(equality_expression
(identifier)
(equality_operator)
(identifier)))
(expression_statement
(relational_expression
(identifier)
(relational_operator)
(identifier)))
(expression_statement
(relational_expression
(identifier)
(relational_operator)
(identifier)))
(expression_statement
(equality_expression
(identifier)
(equality_operator)
(identifier)))
(expression_statement
(logical_and_expression
(identifier)
(logical_and_operator)
(identifier)))
(expression_statement
(logical_or_expression
(identifier)
(logical_or_operator)
(identifier)))
(expression_statement
(bitwise_and_expression
(identifier)
(identifier)))
(expression_statement
(bitwise_or_expression
(identifier)
(identifier)))
(expression_statement
(bitwise_xor_expression
(identifier)
(identifier)))
(expression_statement
(multiplicative_expression
(identifier)
(multiplicative_operator)
(identifier)))
(expression_statement
(shift_expression
(identifier)
(shift_operator)
(identifier)))
(expression_statement
(shift_expression
(identifier)
(shift_operator)
(identifier)))
(expression_statement
(shift_expression
(identifier)
(shift_operator)
(identifier)))
(expression_statement
(additive_expression
(decimal_integer_literal)
(additive_operator)
(decimal_integer_literal)))
(expression_statement
(additive_expression
(decimal_integer_literal)
(additive_operator)
(decimal_integer_literal)))
(expression_statement
(multiplicative_expression
(decimal_integer_literal)
(multiplicative_operator)
(decimal_integer_literal)))
(expression_statement
(multiplicative_expression
(decimal_integer_literal)
(multiplicative_operator)
(decimal_integer_literal))))))
==================================
is expressions
==================================
main() {
a is C.D;
a is List<B>;
c is C;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(type_test_expression
(identifier)
(type_test
(is_operator)
(type_identifier)
(type_identifier))))
(expression_statement
(type_test_expression
(identifier)
(type_test
(is_operator)
(type_identifier)
(type_arguments
(type_identifier)))))
(expression_statement
(type_test_expression
(identifier)
(type_test
(is_operator)
(type_identifier)))))))
===========================================================
if statements
===========================================================
main() {
if (x)
y;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(if_statement
(identifier)
(expression_statement
(identifier))))))
===========================================================
if statements with braces
===========================================================
main() {
if (x) {
y;
}
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(if_statement
(identifier)
(block
(expression_statement
(identifier)))))))
===========================================================
if statements with assignment without braces
===========================================================
main(){
if (x != 3)
y = 2;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(if_statement
(equality_expression
(identifier)
(equality_operator)
(decimal_integer_literal))
(expression_statement
(assignment_expression
(assignable_expression
(identifier))
(decimal_integer_literal)))))))
==================================
if then else statement
==================================
main() {
if (x == 3) {
y = 9;
} else {
y = 0;
}
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(if_statement
(equality_expression
(identifier)
(equality_operator)
(decimal_integer_literal))
(block
(expression_statement
(assignment_expression
(assignable_expression
(identifier))
(decimal_integer_literal))))
(block
(expression_statement
(assignment_expression
(assignable_expression
(identifier))
(decimal_integer_literal))))))))
==================================
nested if then else statements
==================================
main() {
if (a)
if (b)
c();
else
d();
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(if_statement
(identifier)
(if_statement
(identifier)
(expression_statement
(identifier)
(selector
(argument_part
(arguments))))
(expression_statement
(identifier)
(selector
(argument_part
(arguments)))))))))
==================================
ternary expressions
==================================
final max = (a > b) ? a : b;
---
(program
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(conditional_expression
(parenthesized_expression
(relational_expression
(identifier)
(relational_operator)
(identifier)))
(identifier)
(identifier)))))
==================================
for statement
==================================
main() {
for(int i = 1; i < 11; i++) {
print("Count is: " + i);
}
for (j.init(i); j.check(); j.update()) {
print(j);
}
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(for_statement
(for_loop_parts
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(identifier)
(decimal_integer_literal)))
(relational_expression
(identifier)
(relational_operator)
(decimal_integer_literal))
(postfix_expression
(assignable_expression
(identifier))
(postfix_operator
(increment_operator))))
(block
(expression_statement
(identifier)
(selector
(argument_part
(arguments
(argument
(additive_expression
(string_literal)
(additive_operator)
(identifier)))))))))
(for_statement
(for_loop_parts
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(selector
(argument_part
(arguments
(argument
(identifier)))))
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(selector
(argument_part
(arguments)))
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(selector
(argument_part
(arguments))))
(block
(expression_statement
(identifier)
(selector
(argument_part
(arguments
(argument
(identifier)))))))))))
================================
enhanced for statements
================================
main() {
for (A b in c) {
d(b);
}
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(for_statement
(for_loop_parts
(type_identifier)
(identifier)
(identifier))
(block
(expression_statement
(identifier)
(selector
(argument_part
(arguments
(argument
(identifier)))))))))))
================================
await expressions
================================
void main() async {
final id = await Future.delayed(const Duration(seconds: 100));
}
---
(program (function_signature (void_type) (identifier) (formal_parameter_list))
(function_body (block
(local_variable_declaration (initialized_variable_definition (final_builtin) (identifier) (unary_expression
(await_expression (identifier) (selector (unconditional_assignable_selector (identifier)))
(selector (argument_part (arguments (argument
(const_object_expression (const_builtin) (type_identifier)
(arguments (named_argument (label (identifier)) (decimal_integer_literal)))))))))))))))
================================
unary negation expression
================================
void main() {
final remote = false;
if (!remote) {
server = localUrl;
}
}
---
(program (function_signature (void_type) (identifier) (formal_parameter_list))
(function_body (block
(local_variable_declaration (initialized_variable_definition (final_builtin) (identifier) (false)))
(if_statement (unary_expression (prefix_operator (negation_operator)) (identifier))
(block (expression_statement (assignment_expression (assignable_expression (identifier)) (identifier))))))))
================================
assert statement
================================
main() {
assert(x != null);
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(assert_statement
(assertion
(assertion_arguments
(equality_expression
(identifier)
(equality_operator)
(null_literal))))))))
===========================
Type cast in if statement
===========================
main(){
if (data['frame_count'] as int < 5) {
}
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(if_statement
(relational_expression
(type_cast_expression
(identifier)
(selector
(unconditional_assignable_selector
(index_selector
(string_literal))))
(type_cast
(as_operator)
(type_identifier)))
(relational_operator)
(decimal_integer_literal))
(block)))))
===========================
Type cast in if statement parenthesized
===========================
main(){
if ((data['frame_count'] as int) < 5) {
}
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(if_statement
(relational_expression
(parenthesized_expression
(type_cast_expression
(identifier)
(selector
(unconditional_assignable_selector
(index_selector
(string_literal))))
(type_cast
(as_operator)
(type_identifier))))
(relational_operator)
(decimal_integer_literal))
(block)))))
==========================
Simple non-null assertion
==========================
main() {
my!.size = 1;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(assignment_expression
(assignable_expression
(identifier)
(selector)
(unconditional_assignable_selector
(identifier)))
(decimal_integer_literal))))))
==========================
Additional non-null assertion
==========================
main() {
my.size!.run();
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(selector)
(selector
(unconditional_assignable_selector
(identifier)))
(selector
(argument_part
(arguments)))))))
============================
Simple assertion w/o nonnull
============================
main() {
my.size.whatever = 1;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(assignment_expression
(assignable_expression
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(unconditional_assignable_selector
(identifier)))
(decimal_integer_literal))))))
============================
Complex type cast in function call
============================
main() {
printStream(args['json'] as bool ? '' : 'hi');
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(identifier)
(selector
(argument_part
(arguments
(argument
(conditional_expression
(type_cast_expression
(identifier)
(selector
(unconditional_assignable_selector
(index_selector
(string_literal))))
(type_cast
(as_operator)
(type_identifier)))
(string_literal)
(string_literal))))))))))
============================
Complex (parenthesized) type cast in function call
============================
main() {
printStream((args['json'] as bool) ? '' : 'hi');
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(identifier)
(selector
(argument_part
(arguments
(argument
(conditional_expression
(parenthesized_expression
(type_cast_expression
(identifier)
(selector
(unconditional_assignable_selector
(index_selector
(string_literal))))
(type_cast
(as_operator)
(type_identifier))))
(string_literal)
(string_literal))))))))))
==================================
typecast in expression
==================================
main() {
a['json'] as BigB > b;
a < b['json'] as BigB;
a == b as BigB;
a as BigB >= b;
a <= b;
a as BigB != b;
a && b as BigB;
a as BigB || b as BigB;
if (a['json'] as BigB < b as BigB) {
}
a as BigB | b as BigB;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(relational_expression
(type_cast_expression
(identifier)
(selector
(unconditional_assignable_selector
(index_selector
(string_literal))))
(type_cast
(as_operator)
(type_identifier)))
(relational_operator)
(identifier)))
(expression_statement
(relational_expression
(identifier)
(relational_operator)
(type_cast_expression
(identifier)
(selector
(unconditional_assignable_selector
(index_selector
(string_literal))))
(type_cast
(as_operator)
(type_identifier)))))
(expression_statement
(equality_expression
(identifier)
(equality_operator)
(type_cast_expression
(identifier)
(type_cast
(as_operator)
(type_identifier)))))
(expression_statement
(relational_expression
(type_cast_expression
(identifier)
(type_cast
(as_operator)
(type_identifier)))
(relational_operator)
(identifier)))
(expression_statement
(relational_expression
(identifier)
(relational_operator)
(identifier)))
(expression_statement
(equality_expression
(type_cast_expression
(identifier)
(type_cast
(as_operator)
(type_identifier)))
(equality_operator)
(identifier)))
(expression_statement
(logical_and_expression
(identifier)
(logical_and_operator)
(type_cast_expression
(identifier)
(type_cast
(as_operator)
(type_identifier)))))
(expression_statement
(logical_or_expression
(type_cast_expression
(identifier)
(type_cast
(as_operator)
(type_identifier)))
(logical_or_operator)
(type_cast_expression
(identifier)
(type_cast
(as_operator)
(type_identifier)))))
(if_statement
(relational_expression
(type_cast_expression
(identifier)
(selector
(unconditional_assignable_selector
(index_selector
(string_literal))))
(type_cast
(as_operator)
(type_identifier)))
(relational_operator)
(type_cast_expression
(identifier)
(type_cast
(as_operator)
(type_identifier))))
(block))
(expression_statement
(bitwise_or_expression
(type_cast_expression
(identifier)
(type_cast
(as_operator)
(type_identifier)))
(type_cast_expression
(identifier)
(type_cast
(as_operator)
(type_identifier))))))))
=============================
Non-null assignable selector
=============================
main() {
parameters?["charset"];
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(identifier)
(selector
(conditional_assignable_selector
(index_selector
(string_literal))))))))

@ -1,316 +0,0 @@
========================================
simple flutter example
========================================
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container();
}
}
---
(program
(import_or_export
(library_import (import_specification (configurable_uri (uri (string_literal))))))
(function_signature (void_type) (identifier) (formal_parameter_list))
(function_body (block (expression_statement (identifier) (selector (argument_part
(arguments (argument (identifier) (selector (argument_part (arguments))))))))))
(class_definition (identifier) (superclass (type_identifier))
(class_body
(declaration (constant_constructor_signature (const_builtin) (identifier)
(formal_parameter_list (optional_formal_parameters (formal_parameter (type_identifier) (identifier)))))
(initializers (initializer_list_entry (super) (arguments (named_argument (label (identifier)) (identifier))))))
(marker_annotation (identifier))
(method_signature (function_signature (type_identifier) (identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier)))))
(function_body (block (return_statement (identifier) (selector (argument_part (arguments)))))))))
===============================================
ben's flutter error testing
===============================================
class CatalogThumbnailUI extends StatelessWidget {
static const routeName = '/catalog';
CatalogThumbnailUI(this.thread);
final ThreadModel thread;
@override
Widget build(BuildContext context) {
// TODO: implement build
var op = thread.posts.first;
var remainingPosts = thread.posts.getRange(1, thread.posts.length);
var previewRemaining = remainingPosts.map((f) => Column(
children: <Widget>[
Divider(),
Row(children: <Widget>[
Text(f.utc.difference(DateTime.now()).inHours.toString()),
Text(f.text),
Text('...')
],)
],
));
return Card(
child: Column(
children: <Widget>[
Expanded(child: PostUI(op, true)),
...previewRemaining
],
),
);
}
}
------------------------------
(program
(class_definition (identifier) (superclass (type_identifier))
(class_body
(declaration (const_builtin) (static_final_declaration_list (static_final_declaration (identifier) (string_literal))))
(declaration (constructor_signature (identifier)
(formal_parameter_list (formal_parameter (constructor_param (this) (identifier))))))
(declaration (final_builtin) (type_identifier) (initialized_identifier_list (initialized_identifier (identifier))))
(marker_annotation (identifier))
(method_signature
(function_signature (type_identifier) (identifier)
(formal_parameter_list (formal_parameter (type_identifier) (identifier)))))
(function_body
(block (comment)
(local_variable_declaration
(initialized_variable_definition (inferred_type) (identifier) (identifier)
(selector (unconditional_assignable_selector (identifier)))
(selector (unconditional_assignable_selector (identifier)))))
(local_variable_declaration
(initialized_variable_definition (inferred_type) (identifier) (identifier)
(selector (unconditional_assignable_selector (identifier)))
(selector (unconditional_assignable_selector (identifier)))
(selector (argument_part (arguments (argument (decimal_integer_literal)) (argument (identifier)
(selector (unconditional_assignable_selector (identifier)))
(selector (unconditional_assignable_selector (identifier)))))))))
(local_variable_declaration
(initialized_variable_definition (inferred_type) (identifier) (identifier)
(selector (unconditional_assignable_selector (identifier)))
(selector
(argument_part
(arguments
(argument
(function_expression
(formal_parameter_list (formal_parameter (identifier)))
(function_expression_body (identifier)
(selector
(argument_part
(arguments
(named_argument (label (identifier))
(list_literal
(type_arguments (type_identifier)) (identifier)
(selector (argument_part (arguments))) (identifier)
(selector
(argument_part
(arguments
(named_argument (label (identifier))
(list_literal
(type_arguments (type_identifier))
(identifier)
(selector
(argument_part
(arguments (argument (identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(selector
(unconditional_assignable_selector
(identifier)))
(selector
(argument_part
(arguments (argument (identifier)
(selector
(unconditional_assignable_selector (identifier)))
(selector (argument_part (arguments)))))))
(selector
(unconditional_assignable_selector (identifier)))
(selector
(unconditional_assignable_selector (identifier)))
(selector (argument_part (arguments)))))))
(identifier)
(selector
(argument_part
(arguments (argument (identifier)
(selector
(unconditional_assignable_selector (identifier)))))))
(identifier)
(selector
(argument_part
(arguments (argument
(string_literal)))))
))))))))))))))))))
(return_statement
(identifier)
(selector
(argument_part
(arguments
(named_argument
(label (identifier))
(identifier)
(selector
(argument_part
(arguments
(named_argument (label (identifier))
(list_literal
(type_arguments (type_identifier))
(identifier)
(selector
(argument_part
(arguments
(named_argument (label (identifier))
(identifier)
(selector
(argument_part (arguments (argument (identifier)) (argument (true)))))))))
(spread_element (identifier))))))))))))
)))))
======================
Const list constructors
======================
import 'package:flutter/material.dart';
class AWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Row(
children: const [
Flexible(child: ColoredBox(color: Colors.white)),
Flexible(child: ColoredBox(color: Colors.blue))
],
);
}
}
---
(program
(import_or_export (library_import (import_specification (configurable_uri (uri (string_literal))))))
(class_definition (identifier) (superclass (type_identifier))
(class_body (marker_annotation (identifier))
(method_signature (function_signature (type_identifier) (identifier) (formal_parameter_list (formal_parameter (type_identifier) (identifier)))))
(function_body (block
(return_statement (identifier)
(selector (argument_part (arguments (named_argument (label (identifier))
(list_literal (const_builtin) (identifier)
(selector (argument_part (arguments (named_argument (label (identifier)) (identifier)
(selector (argument_part (arguments (named_argument (label (identifier)) (identifier)
(selector (unconditional_assignable_selector (identifier))))))))))) (identifier)
(selector (argument_part (arguments (named_argument (label (identifier)) (identifier)
(selector (argument_part (arguments (named_argument (label (identifier)) (identifier)
(selector (unconditional_assignable_selector (identifier))))))))))))))))))))))
============
Type tearoffs
============
main() {
expect(
tester.widget<RadioMenuButton<int>>(find.byType(RadioMenuButton<int>).first).groupValue,
null,
);
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(identifier)
(selector
(argument_part
(arguments
(argument
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(selector
(argument_part
(type_arguments
(type_identifier)
(type_arguments
(type_identifier)))
(arguments
(argument
(identifier)
(selector
(unconditional_assignable_selector
(identifier)))
(selector
(argument_part
(arguments
(argument
(identifier)
(selector
(type_arguments
(type_identifier)))))))
(selector
(unconditional_assignable_selector
(identifier)))))))
(selector
(unconditional_assignable_selector
(identifier))))
(argument
(null_literal)))))))))
================
Super Parameters
================
class C extends D {
C._({
required super.layoutDirection,
super.creationParams,
}) : super._();
}
---
(program
(class_definition
(identifier)
(superclass
(type_identifier))
(class_body
(declaration
(constructor_signature
(identifier)
(identifier)
(formal_parameter_list
(optional_formal_parameters
(formal_parameter
(super_formal_parameter
(super)
(identifier)))
(formal_parameter
(super_formal_parameter
(super)
(identifier))))))
(initializers
(initializer_list_entry
(super)
(identifier)
(arguments)))))))

@ -1,278 +0,0 @@
========================
decimal integer literals
========================
main() {
123;
4;
50;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(decimal_integer_literal))
(expression_statement
(decimal_integer_literal))
(expression_statement
(decimal_integer_literal)))))
====================
hex integer literals
====================
main() {
0xa_bcd_ef0;
0Xa_bcd_ef0;
0X8000;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(hex_integer_literal))
(expression_statement
(hex_integer_literal))
(expression_statement
(hex_integer_literal)))))
===============================
floating point literals
===============================
main() {
4.23e9;
4.23e-9;
4.23e+9;
40.3e6;
40.3e-6;
1.234;
0.123456;
.12345;
1e4;
0.2e-2;
0.0e-4;
.2e-2;
5.4;
5.4e-10;
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal))
(expression_statement
(decimal_floating_point_literal)))))
================
boolean literals
================
final t = true;
final f = false;
---
(program
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(true)))
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(false))))
===============
string literals
===============
main() {
"";
"\"";
"This is a string";
"'";
'\n';
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(expression_statement
(string_literal))
(expression_statement
(string_literal
(escape_sequence)))
(expression_statement
(string_literal))
(expression_statement
(string_literal))
(expression_statement
(string_literal
(escape_sequence))))))
=============
null literals
=============
final s = null;
---
(program
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(null_literal))))
=============
multiline string literals with single quotes of same type inside
=============
final s = '''
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')
''';
---
(program (final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(string_literal))))
=============
adjacent string concatentation
=============
final str = 'a string'
'another string';
final mixedStr = r'''(["'])((?:\\{2})*|(?:.*?[^\\](?:\\{2})*))\2|''' // with quotes.
r'([^ ]+))';
---
(program
(final_builtin)
(static_final_declaration_list (static_final_declaration (identifier) (string_literal)))
(final_builtin)
(static_final_declaration_list (static_final_declaration (identifier) (string_literal (comment)))))
=============
complex string interpolation
=============
final s = 'ERROR: $error${'\n$stackTrace' ?? ''}';
---
(program
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(string_literal
(template_substitution
(identifier_dollar_escaped))
(template_substitution
(if_null_expression
(string_literal
(escape_sequence)
(template_substitution
(identifier_dollar_escaped)))
(string_literal)))))))
=============
raw strings single
=============
final s = r'\';
final s1 = r'''\''';
---
(program
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(string_literal)))
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(string_literal))))
=============
raw strings double
=============
final s = r"\";
final s1 = r"""\""";
---
(program
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(string_literal)))
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(string_literal))))

@ -1,604 +0,0 @@
==================================
while statement
==================================
class WhileDemo {
void main(String args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
---
(program
(class_definition
name: (identifier)
body: (class_body
(method_signature
(function_signature
(void_type)
name: (identifier)
(formal_parameter_list
(formal_parameter
(type_identifier)
name: (identifier)))
)
)
(function_body
(block
(local_variable_declaration (initialized_variable_definition
(type_identifier)
name: (identifier)
value: (decimal_integer_literal)))
(while_statement
condition: (parenthesized_expression
(relational_expression
(identifier)
(relational_operator)
(decimal_integer_literal)))
body: (block
(expression_statement
(identifier)
(selector
(unconditional_assignable_selector (identifier))
)
(selector
(unconditional_assignable_selector (identifier))
)
(selector
(argument_part (arguments
(argument (additive_expression
(string_literal)
(additive_operator)
(identifier)
))
))
)
)
(expression_statement
(postfix_expression (assignable_expression (identifier)) (postfix_operator (increment_operator)))
)
)
)
)
)
)
)
)
==================================
try-with-resources statements
==================================
get a {
var a;
try {
int data = input.read();
} on Exception catch (e) {
a();
}
}
---
(program
(getter_signature
name: (identifier))
(function_body
(block
(local_variable_declaration (initialized_variable_definition (inferred_type) name: (identifier)))
(try_statement
body: (block
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
name: (identifier)
value: (identifier)
value:
(selector
(unconditional_assignable_selector (identifier))
)
value:
(selector
(argument_part
(arguments)
)
)
)
)
)
(type_identifier)
(catch_clause
(catch_parameters (identifier)))
(block
(expression_statement
(identifier)
(selector
(argument_part
(arguments)
)
)
)
)
)
)
)
)
==================================
return statement
==================================
main() {
return x;
return x * y;
return x + 2;
return fire(x);
}
---
(program
(function_signature
(identifier)
(formal_parameter_list))
(function_body
(block
(return_statement
(identifier))
(return_statement
(multiplicative_expression
(identifier)
(multiplicative_operator)
(identifier)))
(return_statement
(additive_expression
(identifier)
(additive_operator)
(decimal_integer_literal)))
(return_statement
(identifier)
(selector
(argument_part
(arguments
(argument
(identifier)))))))))
==================================
annotation
==================================
@SuppressWarnings(value = "unchecked")
@GwtCompatible(emulated = true)
class Duck {
}
---
(program
(class_definition
(annotation
(identifier)
(arguments
(argument
(assignment_expression
(assignable_expression
(identifier))
(string_literal)))))
(annotation
(identifier)
(arguments
(argument
(assignment_expression
(assignable_expression
(identifier))
(true)))))
(identifier)
(class_body)))
==================================
marker annotation
==================================
@Override
class Quack {
@bar
void foo() {
}
}
---
(program
(class_definition
(marker_annotation
(identifier))
(identifier)
(class_body
(marker_annotation
(identifier))
(method_signature
(function_signature
(void_type)
(identifier)
(formal_parameter_list)))
(function_body
(block)))))
==================================
single element annotation
==================================
@Duck(waddle.swim)
@SuppressWarnings("unchecked")
class Quack {
}
---
(program
(class_definition
(annotation
(identifier)
(arguments
(argument
(identifier)
(selector
(unconditional_assignable_selector
(identifier))))))
(annotation
(identifier)
(arguments
(argument
(string_literal))))
(identifier)
(class_body)))
==================================
lambda expression
==================================
class LambdaTest {
void singleton() {
var b = (Str version) => create;
var d = (Str a) {
int destinysChild = 2;
};
}
}
---
(program
(class_definition
(identifier)
(class_body
(method_signature (function_signature
(void_type)
(identifier)
(formal_parameter_list)))
(function_body
(block
(local_variable_declaration
(initialized_variable_definition (inferred_type) (identifier)
(function_expression
(formal_parameter_list (formal_parameter (type_identifier) (identifier)))
(function_expression_body (identifier))
)
)
)
(local_variable_declaration
(initialized_variable_definition
(inferred_type) (identifier) (function_expression
(formal_parameter_list (formal_parameter (type_identifier) (identifier)) )
(function_expression_body
(block
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(identifier)
(decimal_integer_literal)))
)))
)
))
))))
==================================
switch statement
==================================
class SwitchDemo {
static void main(String args) {
int destinysChild = 2;
String destinysChildString;
switch (destinysChild) {
case 1: destinysChildString = "Beyonce";
break;
case 2: destinysChildString = "Kelly";
break;
case 3: destinysChildString = "Michelle";
break;
default: destinysChildString = "Invalid";
break;
}
System.out.println(destinysChildString);
}
}
---
(program
(class_definition
name: (identifier)
body: (class_body
(method_signature (function_signature
(void_type)
name: (identifier)
(formal_parameter_list
(formal_parameter
(type_identifier)
name: (identifier)
)
)
))
(function_body (block
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
name: (identifier)
value: (decimal_integer_literal)
)
)
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
name: (identifier)
)
)
(switch_statement
condition: (parenthesized_expression (identifier))
body: (switch_block
(switch_statement_case
(case_builtin)
(constant_pattern
(decimal_integer_literal))
(expression_statement
(assignment_expression
left: (assignable_expression
(identifier))
right: (string_literal)))
(break_statement))
(switch_statement_case
(case_builtin)
(constant_pattern
(decimal_integer_literal))
(expression_statement
(assignment_expression
left: (assignable_expression
(identifier))
right: (string_literal)))
(break_statement))
(switch_statement_case
(case_builtin)
(constant_pattern
(decimal_integer_literal))
(expression_statement
(assignment_expression
left: (assignable_expression
(identifier))
right: (string_literal)))
(break_statement))
(switch_statement_default
(expression_statement
(assignment_expression
left: (assignable_expression
(identifier))
right: (string_literal)))
(break_statement))))
(expression_statement
(identifier)
(selector
(unconditional_assignable_selector (identifier))
)
(selector
(unconditional_assignable_selector (identifier))
)
(selector
(argument_part (arguments (argument (identifier))))
)
)
)
)
)
)
)
==================================
type arguments
==================================
class Box <T> {
T theObject;
Box( T arg) { theObject = arg; }
// more code
}
---
(program
(class_definition
(identifier)
(type_parameters
(type_parameter
(type_identifier)))
(class_body
(declaration
(type_identifier)
(initialized_identifier_list (initialized_identifier (identifier)))
)
(method_signature (constructor_signature
(identifier)
(formal_parameter_list
(formal_parameter
(type_identifier)
(identifier)))))
(function_body
(block (expression_statement (assignment_expression
(assignable_expression (identifier))
(identifier)))))
(comment))))
==================================
wildcard
==================================
class WildcardDemo {
List<B> a;
}
---
(program
(class_definition
(identifier)
(class_body
(declaration
(type_identifier)
(type_arguments
(type_identifier))
(initialized_identifier_list (initialized_identifier (identifier)))
))))
==================================
type arguments with generic types
==================================
class someClass <T> {
List<T> someMethod() {
List< T > list = Collections.emptyList<S>();
emptyList<S, H>(g);
return list;
}
void anotherMethod<T>(S arg) {
List< S > list = Collections.emptyList<S>();
}
}
---
(program
(class_definition
(identifier)
(type_parameters
(type_parameter
(type_identifier)))
(class_body
(method_signature (function_signature
(type_identifier)
(type_arguments (type_identifier))
(identifier)
(formal_parameter_list)
))
(function_body (block
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(type_arguments (type_identifier))
(identifier)
(identifier)
(selector
(unconditional_assignable_selector (identifier))
)
(selector
(argument_part
(type_arguments
(type_identifier)
)
(arguments)
)
)
)
)
(expression_statement
(identifier)
(selector
(argument_part
(type_arguments
(type_identifier)
(type_identifier)
)
(arguments (argument (identifier)))
)
)
)
(return_statement (identifier))))
(method_signature (function_signature
(void_type)
(identifier)
(type_parameters
(type_parameter
(type_identifier)))
(formal_parameter_list
(formal_parameter
(type_identifier)
(identifier)))
))
(function_body (block
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(type_arguments (type_identifier))
(identifier)
(identifier)
(selector
(unconditional_assignable_selector
(identifier)
)
)
(selector
(argument_part
(type_arguments
(type_identifier)
) (arguments)
)
)
)
)
)
)
)
)
)
==================================
empty type arguments
==================================
Box<Integer> integerBox = new Box<>();
---
(program
(type_identifier) (type_arguments (type_identifier))
(initialized_identifier_list
(initialized_identifier (identifier)
(new_expression (type_identifier) (type_arguments) (arguments)))))

@ -1,115 +0,0 @@
=====================
Variable declaration
=====================
void record() {
var (i as int, String s) = record;
}
---
(program
(function_signature
(void_type)
(identifier)
(formal_parameter_list))
(function_body
(block
(local_variable_declaration
(pattern_variable_declaration
(inferred_type)
(record_pattern
(cast_pattern
(constant_pattern
(identifier))
(type_identifier))
(variable_pattern
(type_identifier)
(identifier)))
(identifier))))))
============================
Switch statement relational
============================
void main(){
switch (obj) {
case >= first && <= last:
print('in range');
default:
}
}
---
(program
(function_signature
(void_type)
(identifier)
(formal_parameter_list))
(function_body
(block
(switch_statement
(parenthesized_expression
(identifier))
(switch_block
(switch_statement_case
(case_builtin)
(relational_operator)
(identifier)
(logical_and_operator)
(relational_operator)
(identifier)
(expression_statement
(identifier)
(selector
(argument_part
(arguments
(argument
(string_literal)))))))
(switch_statement_default))))))
============================
For loop pattern
============================
void main() {
// ERROR
for (var MapEntry(key: key, value: count) in hist.entries) {
print('$key occurred $count times');
}
}
---
(program
(function_signature
(void_type)
(identifier)
(formal_parameter_list))
(function_body
(block
(comment)
(for_statement
(for_loop_parts
(inferred_type)
(object_pattern
(type_identifier)
(identifier)
(constant_pattern
(identifier))
(identifier)
(constant_pattern
(identifier)))
(identifier)
(selector
(unconditional_assignable_selector
(identifier))))
(block
(expression_statement
(identifier)
(selector
(argument_part
(arguments
(argument
(string_literal
(template_substitution
(identifier_dollar_escaped))
(template_substitution
(identifier_dollar_escaped)))))))))))))

@ -1,316 +0,0 @@
===============
Record Literals
===============
final y = (1, 2, await x);
final z = (a: 1, b: 4);
final a = (1,);
final b = (a: 1);
final c = (a: 1, b: 2,);
final d = (a, b, x: 4, c, d);
final e = (1, 2,);
---
(program
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(record_literal
(record_field
(decimal_integer_literal))
(record_field
(decimal_integer_literal))
(record_field
(unary_expression
(await_expression
(identifier)))))))
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(record_literal
(record_field
(label
(identifier))
(decimal_integer_literal))
(record_field
(label
(identifier))
(decimal_integer_literal)))))
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(record_literal
(decimal_integer_literal))))
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(record_literal
(label
(identifier))
(decimal_integer_literal))))
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(record_literal
(record_field
(label
(identifier))
(decimal_integer_literal))
(record_field
(label
(identifier))
(decimal_integer_literal)))))
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(record_literal
(record_field
(identifier))
(record_field
(identifier))
(record_field
(label
(identifier))
(decimal_integer_literal))
(record_field
(identifier))
(record_field
(identifier)))))
(final_builtin)
(static_final_declaration_list
(static_final_declaration
(identifier)
(record_literal
(record_field
(decimal_integer_literal))
(record_field
(decimal_integer_literal))))))
======================================================
Records in function and class bounds, and local types
======================================================
class C2<T extends (num, {Object o})> {
T t;
C2(this.t);
}
T bar<T extends (num, {Object o})>(T t) => t;
void main() {
(num, String) a1 = (1.2, "s");
}
---
(program
(class_definition
(identifier)
(type_parameters
(type_parameter
(type_identifier)
(type_bound
(record_type
(record_type_field
(type_identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier)))))))
(class_body
(declaration
(type_identifier)
(initialized_identifier_list
(initialized_identifier
(identifier))))
(declaration
(constructor_signature
(identifier)
(formal_parameter_list
(formal_parameter
(constructor_param
(this)
(identifier))))))))
(function_signature
(type_identifier)
(identifier)
(type_parameters
(type_parameter
(type_identifier)
(type_bound
(record_type
(record_type_field
(type_identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier)))))))
(formal_parameter_list
(formal_parameter
(type_identifier)
(identifier))))
(function_body
(identifier))
(function_signature
(void_type)
(identifier)
(formal_parameter_list))
(function_body
(block
(local_variable_declaration
(initialized_variable_definition
(record_type
(record_type_field
(type_identifier))
(record_type_field
(type_identifier)))
(identifier)
(record_literal
(record_field
(decimal_floating_point_literal))
(record_field
(string_literal))))))))
===============
Record Typedefs
===============
typedef R1 = (int $6, {String s});
typedef R2 = (int, {String $101});
typedef (int $1, {int i}) R3();
typedef (int, {int $2}) R4();
typedef void R5((String s, {String $2}) r);
(int, {int $2})? foo1() => null;
(int $3, {int x})? foo2() => null;
void bar1((int i, {bool $2}) r) {}
void bar2((int $4, {bool b}) r) {}
---
(program
(type_alias
(type_identifier)
(record_type
(record_type_field
(type_identifier)
(identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier)))))
(type_alias
(type_identifier)
(record_type
(record_type_field
(type_identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier)))))
(type_alias
(record_type
(record_type_field
(type_identifier)
(identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier))))
(type_identifier)
(formal_parameter_list))
(type_alias
(record_type
(record_type_field
(type_identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier))))
(type_identifier)
(formal_parameter_list))
(type_alias
(void_type)
(type_identifier)
(formal_parameter_list
(formal_parameter
(record_type
(record_type_field
(type_identifier)
(identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier))))
(identifier))))
(function_signature
(record_type
(record_type_field
(type_identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier))))
(nullable_type)
(identifier)
(formal_parameter_list))
(function_body
(null_literal))
(function_signature
(record_type
(record_type_field
(type_identifier)
(identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier))))
(nullable_type)
(identifier)
(formal_parameter_list))
(function_body
(null_literal))
(function_signature
(void_type)
(identifier)
(formal_parameter_list
(formal_parameter
(record_type
(record_type_field
(type_identifier)
(identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier))))
(identifier))))
(function_body
(block))
(function_signature
(void_type)
(identifier)
(formal_parameter_list
(formal_parameter
(record_type
(record_type_field
(type_identifier)
(identifier))
(record_type_named_field
(typed_identifier
(type_identifier)
(identifier))))
(identifier))))
(function_body
(block)))

@ -1,104 +0,0 @@
===============
integral types
===============
class Beyonce {
int formation() {
int x;
byte x;
short x;
long x;
char x;
}
}
---
(program
(class_definition
(identifier)
(class_body
(method_signature
(function_signature
(type_identifier)
(identifier)
(formal_parameter_list)
)
)
(function_body
(block
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(identifier)))
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(identifier)
))
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(identifier)
))
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(identifier)
))
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(identifier)
))
)
)
)
)
)
=====================
floating point types
=====================
class Beyonce {
int formation() {
float x;
double x;
}
}
---
(program
(class_definition
(identifier)
(class_body
(method_signature
(function_signature
(type_identifier)
(identifier)
(formal_parameter_list)
)
)
(function_body
(block
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(identifier)
))
(local_variable_declaration
(initialized_variable_definition
(type_identifier)
(identifier)
))))
)))

@ -1,25 +0,0 @@
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container();
}
}
Future<void> hello() async {
// <- keyword
}
Stream<String> helloStream() async* {
// <- keyword
}
Iterable<String> helloIter() sync* {
// <- keyword
}

@ -1,44 +0,0 @@
enum Material {
// ^ type
DENIM,
CANVAS
}
class Person {
// ^ type
String name;
Person(String name) {
// <- type
// ^ type
this.name = name;
this.pants = new Pants<Pocket>();
// ^ type
// ^ type
}
String getName() {
// <- type
// ^ method
// The above used to be 'function.method', not 'method'. Fix it?
return this.name;
return Material.DENIM;
}
}
class Collections {
static List<T> emptyList<T>() {
return [];
}
}
class someClass<T> {
List<T> someMethod() {
List<T> list = Collections.emptyList<T>();
return list;
}
void anotherMethod<S>(S arg) {
List<S> list = Collections.emptyList<S>();
}
}

@ -1,8 +0,0 @@
#!/bin/bash
dart tester/test.dart $1
## USAGE
# ./test_all.sh ~/flutter
# Or whatever directory you want to find all errors in
# Edit test.dart to change how many error lines it prints
# Default maximum is 100 lines, so you don't get endless errors printing out

@ -1,9 +0,0 @@
name: tree_sitter_dart_tester
environment:
sdk: '>=3.0.0-0 <3.2.0'
dependencies:
glob: ^2.1.1
path: ^1.8.3
dev_dependencies:
dcli: ^2.1.0

@ -1,105 +0,0 @@
#! /usr/bin/env dcli
import 'dart:io';
// import 'package:dcli/dcli.dart';
import 'package:path/path.dart';
var lines = 0;
final sectionSize = 100;
final maxPrint = 500;
var linesPrinted = 0;
var errorLines = 0;
void main(List<String> args) async {
if (args.length < 2) {
print(
"Usage: dart tester/test.dart /path/to/directory/for/testing parse/highlight/query [query.scm]");
return;
}
if (File(args[0]).existsSync()) {
await runTreeSitterSingle(
[args[0]], args[1], args.length == 3 ? args[2] : null);
return;
}
final files = Directory(args[0])
.listSync(recursive: true)
.whereType<File>()
.where((e) => e.path.endsWith('.dart'))
.map((f) => f.path)
.toList();
final results = <Future<void>>[];
for (var i = 0; i < files.length; i += sectionSize) {
final sublist = files.sublist(
i, i + sectionSize < files.length ? i + sectionSize : files.length);
results.add(
runTreeSitter(sublist, args[1], args.length == 3 ? args[2] : null));
}
await Future.wait(results);
print('Processed $lines lines of tree-sitter output');
print('Error lines $errorLines');
print('Error percentage ${errorLines * 100 / lines}%');
}
Future<void> runTreeSitterSingle(
List<String> files, String parseOrHighlight, String? queryFile) async {
assert(files.length == 1);
try {
final result = await Process.run(
absolute('node_modules/tree-sitter-cli/tree-sitter'), [
if (parseOrHighlight == 'query') ...['query', queryFile!] else
parseOrHighlight,
...files
]);
var lastLine = "";
var prevLastLine = "";
var hadError = false;
var lineErrors = "";
for (final line in result.stdout.split('\n')) {
prevLastLine = lastLine;
lastLine = line + "\n";
lines++;
if (line.contains('ERROR')) {
errorLines++;
lineErrors += line + "\n";
hadError = true;
}
}
if (hadError) {
print(prevLastLine);
print(lineErrors);
}
} catch (e) {
print('Serious error on $parseOrHighlight in $files');
print(e);
}
}
Future<void> runTreeSitter(
List<String> files, String parseOrHighlight, String? queryFile) async {
try {
final result = await Process.run(
absolute('node_modules/tree-sitter-cli/tree-sitter'), [
if (parseOrHighlight == 'query') ...['query', queryFile!] else
parseOrHighlight,
...files
]);
for (final line in result.stdout.split('\n')) {
lines++;
if (line.contains('ERROR')) {
errorLines++;
if (linesPrinted < maxPrint) {
linesPrinted++;
print(line);
}
}
}
} catch (e) {
print('Serious error on $parseOrHighlight in $files');
print(e);
}
}

@ -1,172 +0,0 @@
<head>
<meta charset="utf-8">
<title>tree-sitter THE_LANGUAGE_NAME</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.45.0/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/clusterize.js/0.18.0/clusterize.min.css">
<link rel="icon" type="image/png" href="http://tree-sitter.github.io/tree-sitter/assets/images/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="http://tree-sitter.github.io/tree-sitter/assets/images/favicon-16x16.png" sizes="16x16" />
</head>
<body>
<div id="playground-container" style="visibility: hidden;">
<header>
<div class=header-item>
<bold>THE_LANGUAGE_NAME</bold>
</div>
<div class=header-item>
<label for="logging-checkbox">log</label>
<input id="logging-checkbox" type="checkbox"></input>
</div>
<div class=header-item>
<label for="query-checkbox">query</label>
<input id="query-checkbox" type="checkbox"></input>
</div>
<div class=header-item>
<label for="update-time">parse time: </label>
<span id="update-time"></span>
</div>
<select id="language-select" style="display: none;">
<option value="parser">Parser</option>
</select>
</header>
<main>
<div id="input-pane">
<div id="code-container">
<textarea id="code-input"></textarea>
</div>
<div id="query-container" style="visibility: hidden; position: absolute;">
<textarea id="query-input"></textarea>
</div>
</div>
<div id="output-container-scroll">
<pre id="output-container" class="highlight"></pre>
</div>
</main>
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.45.0/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clusterize.js/0.18.0/clusterize.min.js"></script>
<script>LANGUAGE_BASE_URL = "./";</script>
<script src=assets/tree-sitter.js></script>
<script src=assets/playground.js></script>
<style>
body {
margin: 0;
padding: 0;
}
#playground-container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
header {
box-sizing: border-box;
display: flex;
padding: 20px;
height: 60px;
border-bottom: 1px solid #aaa;
}
main {
flex: 1;
position: relative;
}
#input-pane {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 50%;
display: flex;
flex-direction: column;
}
#code-container, #query-container {
flex: 1;
position: relative;
overflow: hidden;
border-right: 1px solid #aaa;
border-bottom: 1px solid #aaa;
}
#output-container-scroll {
position: absolute;
top: 0;
left: 50%;
bottom: 0;
right: 0;
}
.header-item {
margin-right: 30px;
}
#playground-container .CodeMirror {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
}
#output-container-scroll {
flex: 1;
padding: 0;
overflow: auto;
}
#output-container {
padding: 0 10px;
margin: 0;
}
#logging-checkbox {
vertical-align: middle;
}
.CodeMirror div.CodeMirror-cursor {
border-left: 3px solid red;
}
a {
text-decoration: none;
color: #040404;
padding: 2px;
}
a:hover {
text-decoration: underline;
}
a.highlighted {
background-color: #d9d9d9;
color: red;
border-radius: 3px;
text-decoration: underline;
}
.query-error {
text-decoration: underline red dashed;
-webkit-text-decoration: underline red dashed;
}
</style>
</body>

@ -1,3 +0,0 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/

@ -1,5 +0,0 @@
## 0.1.1
- Added some idiomatic dart apis
## 0.1.0
- Initial version.

@ -1,7 +0,0 @@
Copyright 2023 Tim Whiting
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -1,16 +0,0 @@
ifeq ($(shell uname),Darwin)
SOEXT = dylib
else
SOEXT = so
endif
dart: tree-sitter
clang -Isrc -Itree-sitter/lib/include ../src/parser.c ../src/scanner.c tree-sitter/libtree-sitter.a --shared -o libdart.$(SOEXT)
cp tree-sitter/libtree-sitter.so .
cp tree-sitter/libtree-sitter.dylib .
cp tree-sitter/tree-sitter.dll .
tree-sitter:
cd tree-sitter && make
all: dart

@ -1,35 +0,0 @@
# Tree Sitter Dart Library
This library provides Dart bindings for the [Tree Sitter](http://tree-sitter.github.io/tree-sitter/) c parsing library. It allows parsing source code into a syntax tree that you can traverse and query.
## Installation
You must have the tree sitter library available as a dynamic library on your system.
Then set the library location using:
```dart
TreeSitterConfig.setLibraryPath('/path/to/libtree-sitter.so');
```
Next create a parser for your language by first creating a dynamic library for your language's grammar.
Then load and use the parser:
```dart
import 'package:ffi/ffi.dart';
import 'package:tree_sitter/tree_sitter.dart';
void main() {
final parser =
Parser(sharedLibrary: 'libdart.dylib', entryPoint: 'tree_sitter_dart');
final program = "class A {}";
final tree = parser.parse(program);
print(tree.root.string);
}
```
You can access other apis via the top level `treeSitterApi` ffi wrapper
Or you can help contribute to an idiomatic dart api on top of the ffi wrapper.
Many of the apis are started but not complete.
Expect breaking changes while we figure out the best api

@ -1,30 +0,0 @@
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.
include: package:lints/recommended.yaml
# Uncomment the following section to specify additional rules.
# linter:
# rules:
# - camel_case_types
# analyzer:
# exclude:
# - path/to/excluded/files/**
# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints
# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options

@ -1,16 +0,0 @@
name: "TreeSitter"
description: "C Bindings to the TreeSitter library"
output: 'lib/src/generated_bindings.dart'
headers:
entry-points:
- 'tree-sitter/lib/include/tree_sitter/api.h'
include-directives:
- 'tree-sitter/lib/include/tree_sitter/api.h'
functions:
symbol-address:
include:
- 'ts_parser_delete'
- 'ts_tree_delete'
- 'ts_tree_cursor_delete'
- 'ts_query_delete'
- 'ts_query_cursor_delete'

@ -1,48 +0,0 @@
import 'dart:convert';
import 'dart:io';
import 'package:args/args.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'gen_grammar.freezed.dart';
part 'gen_grammar.g.dart';
@freezed
class Type with _$Type {
const factory Type({
required String type,
required bool named,
@Default({}) Map<String, Field> fields,
Field? children,
@Default([]) List<Type> subtypes,
}) = _Type;
factory Type.fromJson(Map<String, dynamic> map) => _$TypeFromJson(map);
}
@freezed
class Field with _$Field {
const factory Field({
required bool multiple,
required bool required,
@Default([]) List<Type> types,
}) = _Field;
factory Field.fromJson(Map<String, dynamic> map) => _$FieldFromJson(map);
}
final genParser = ArgParser()
..addOption('input',
abbr: 'i', help: 'Grammar\'s Node Types file', mandatory: true)
..addOption('output', abbr: 'o', help: 'Output file');
final parser = ArgParser()..addCommand('gen', genParser);
Future<void> main(List<String> args) async {
final results = parser.parse(args);
final input = results.command!['input'] as String;
final j = json.decode(File(input).readAsStringSync());
final result = (j as List<dynamic>)
.map((d) => Type.fromJson(d as Map<String, dynamic>))
.toList();
print(result);
final output =
results.command?['output'] as String? ?? 'lib/src/grammar.dart';
}

@ -1,442 +0,0 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'gen_grammar.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods');
Type _$TypeFromJson(Map<String, dynamic> json) {
return _Type.fromJson(json);
}
/// @nodoc
mixin _$Type {
String get type => throw _privateConstructorUsedError;
bool get named => throw _privateConstructorUsedError;
Map<String, Field> get fields => throw _privateConstructorUsedError;
Field? get children => throw _privateConstructorUsedError;
List<Type> get subtypes => throw _privateConstructorUsedError;
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$TypeCopyWith<Type> get copyWith => throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $TypeCopyWith<$Res> {
factory $TypeCopyWith(Type value, $Res Function(Type) then) =
_$TypeCopyWithImpl<$Res, Type>;
@useResult
$Res call(
{String type,
bool named,
Map<String, Field> fields,
Field? children,
List<Type> subtypes});
$FieldCopyWith<$Res>? get children;
}
/// @nodoc
class _$TypeCopyWithImpl<$Res, $Val extends Type>
implements $TypeCopyWith<$Res> {
_$TypeCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
@pragma('vm:prefer-inline')
@override
$Res call({
Object? type = null,
Object? named = null,
Object? fields = null,
Object? children = freezed,
Object? subtypes = null,
}) {
return _then(_value.copyWith(
type: null == type
? _value.type
: type // ignore: cast_nullable_to_non_nullable
as String,
named: null == named
? _value.named
: named // ignore: cast_nullable_to_non_nullable
as bool,
fields: null == fields
? _value.fields
: fields // ignore: cast_nullable_to_non_nullable
as Map<String, Field>,
children: freezed == children
? _value.children
: children // ignore: cast_nullable_to_non_nullable
as Field?,
subtypes: null == subtypes
? _value.subtypes
: subtypes // ignore: cast_nullable_to_non_nullable
as List<Type>,
) as $Val);
}
@override
@pragma('vm:prefer-inline')
$FieldCopyWith<$Res>? get children {
if (_value.children == null) {
return null;
}
return $FieldCopyWith<$Res>(_value.children!, (value) {
return _then(_value.copyWith(children: value) as $Val);
});
}
}
/// @nodoc
abstract class _$$_TypeCopyWith<$Res> implements $TypeCopyWith<$Res> {
factory _$$_TypeCopyWith(_$_Type value, $Res Function(_$_Type) then) =
__$$_TypeCopyWithImpl<$Res>;
@override
@useResult
$Res call(
{String type,
bool named,
Map<String, Field> fields,
Field? children,
List<Type> subtypes});
@override
$FieldCopyWith<$Res>? get children;
}
/// @nodoc
class __$$_TypeCopyWithImpl<$Res> extends _$TypeCopyWithImpl<$Res, _$_Type>
implements _$$_TypeCopyWith<$Res> {
__$$_TypeCopyWithImpl(_$_Type _value, $Res Function(_$_Type) _then)
: super(_value, _then);
@pragma('vm:prefer-inline')
@override
$Res call({
Object? type = null,
Object? named = null,
Object? fields = null,
Object? children = freezed,
Object? subtypes = null,
}) {
return _then(_$_Type(
type: null == type
? _value.type
: type // ignore: cast_nullable_to_non_nullable
as String,
named: null == named
? _value.named
: named // ignore: cast_nullable_to_non_nullable
as bool,
fields: null == fields
? _value._fields
: fields // ignore: cast_nullable_to_non_nullable
as Map<String, Field>,
children: freezed == children
? _value.children
: children // ignore: cast_nullable_to_non_nullable
as Field?,
subtypes: null == subtypes
? _value._subtypes
: subtypes // ignore: cast_nullable_to_non_nullable
as List<Type>,
));
}
}
/// @nodoc
@JsonSerializable()
class _$_Type implements _Type {
const _$_Type(
{required this.type,
required this.named,
final Map<String, Field> fields = const {},
this.children,
final List<Type> subtypes = const []})
: _fields = fields,
_subtypes = subtypes;
factory _$_Type.fromJson(Map<String, dynamic> json) => _$$_TypeFromJson(json);
@override
final String type;
@override
final bool named;
final Map<String, Field> _fields;
@override
@JsonKey()
Map<String, Field> get fields {
if (_fields is EqualUnmodifiableMapView) return _fields;
// ignore: implicit_dynamic_type
return EqualUnmodifiableMapView(_fields);
}
@override
final Field? children;
final List<Type> _subtypes;
@override
@JsonKey()
List<Type> get subtypes {
if (_subtypes is EqualUnmodifiableListView) return _subtypes;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_subtypes);
}
@override
String toString() {
return 'Type(type: $type, named: $named, fields: $fields, children: $children, subtypes: $subtypes)';
}
@override
bool operator ==(dynamic other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$_Type &&
(identical(other.type, type) || other.type == type) &&
(identical(other.named, named) || other.named == named) &&
const DeepCollectionEquality().equals(other._fields, _fields) &&
(identical(other.children, children) ||
other.children == children) &&
const DeepCollectionEquality().equals(other._subtypes, _subtypes));
}
@JsonKey(ignore: true)
@override
int get hashCode => Object.hash(
runtimeType,
type,
named,
const DeepCollectionEquality().hash(_fields),
children,
const DeepCollectionEquality().hash(_subtypes));
@JsonKey(ignore: true)
@override
@pragma('vm:prefer-inline')
_$$_TypeCopyWith<_$_Type> get copyWith =>
__$$_TypeCopyWithImpl<_$_Type>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$_TypeToJson(
this,
);
}
}
abstract class _Type implements Type {
const factory _Type(
{required final String type,
required final bool named,
final Map<String, Field> fields,
final Field? children,
final List<Type> subtypes}) = _$_Type;
factory _Type.fromJson(Map<String, dynamic> json) = _$_Type.fromJson;
@override
String get type;
@override
bool get named;
@override
Map<String, Field> get fields;
@override
Field? get children;
@override
List<Type> get subtypes;
@override
@JsonKey(ignore: true)
_$$_TypeCopyWith<_$_Type> get copyWith => throw _privateConstructorUsedError;
}
Field _$FieldFromJson(Map<String, dynamic> json) {
return _Field.fromJson(json);
}
/// @nodoc
mixin _$Field {
bool get multiple => throw _privateConstructorUsedError;
bool get required => throw _privateConstructorUsedError;
List<Type> get types => throw _privateConstructorUsedError;
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$FieldCopyWith<Field> get copyWith => throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $FieldCopyWith<$Res> {
factory $FieldCopyWith(Field value, $Res Function(Field) then) =
_$FieldCopyWithImpl<$Res, Field>;
@useResult
$Res call({bool multiple, bool required, List<Type> types});
}
/// @nodoc
class _$FieldCopyWithImpl<$Res, $Val extends Field>
implements $FieldCopyWith<$Res> {
_$FieldCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
@pragma('vm:prefer-inline')
@override
$Res call({
Object? multiple = null,
Object? required = null,
Object? types = null,
}) {
return _then(_value.copyWith(
multiple: null == multiple
? _value.multiple
: multiple // ignore: cast_nullable_to_non_nullable
as bool,
required: null == required
? _value.required
: required // ignore: cast_nullable_to_non_nullable
as bool,
types: null == types
? _value.types
: types // ignore: cast_nullable_to_non_nullable
as List<Type>,
) as $Val);
}
}
/// @nodoc
abstract class _$$_FieldCopyWith<$Res> implements $FieldCopyWith<$Res> {
factory _$$_FieldCopyWith(_$_Field value, $Res Function(_$_Field) then) =
__$$_FieldCopyWithImpl<$Res>;
@override
@useResult
$Res call({bool multiple, bool required, List<Type> types});
}
/// @nodoc
class __$$_FieldCopyWithImpl<$Res> extends _$FieldCopyWithImpl<$Res, _$_Field>
implements _$$_FieldCopyWith<$Res> {
__$$_FieldCopyWithImpl(_$_Field _value, $Res Function(_$_Field) _then)
: super(_value, _then);
@pragma('vm:prefer-inline')
@override
$Res call({
Object? multiple = null,
Object? required = null,
Object? types = null,
}) {
return _then(_$_Field(
multiple: null == multiple
? _value.multiple
: multiple // ignore: cast_nullable_to_non_nullable
as bool,
required: null == required
? _value.required
: required // ignore: cast_nullable_to_non_nullable
as bool,
types: null == types
? _value._types
: types // ignore: cast_nullable_to_non_nullable
as List<Type>,
));
}
}
/// @nodoc
@JsonSerializable()
class _$_Field implements _Field {
const _$_Field(
{required this.multiple,
required this.required,
final List<Type> types = const []})
: _types = types;
factory _$_Field.fromJson(Map<String, dynamic> json) =>
_$$_FieldFromJson(json);
@override
final bool multiple;
@override
final bool required;
final List<Type> _types;
@override
@JsonKey()
List<Type> get types {
if (_types is EqualUnmodifiableListView) return _types;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_types);
}
@override
String toString() {
return 'Field(multiple: $multiple, required: $required, types: $types)';
}
@override
bool operator ==(dynamic other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$_Field &&
(identical(other.multiple, multiple) ||
other.multiple == multiple) &&
(identical(other.required, required) ||
other.required == required) &&
const DeepCollectionEquality().equals(other._types, _types));
}
@JsonKey(ignore: true)
@override
int get hashCode => Object.hash(runtimeType, multiple, required,
const DeepCollectionEquality().hash(_types));
@JsonKey(ignore: true)
@override
@pragma('vm:prefer-inline')
_$$_FieldCopyWith<_$_Field> get copyWith =>
__$$_FieldCopyWithImpl<_$_Field>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$_FieldToJson(
this,
);
}
}
abstract class _Field implements Field {
const factory _Field(
{required final bool multiple,
required final bool required,
final List<Type> types}) = _$_Field;
factory _Field.fromJson(Map<String, dynamic> json) = _$_Field.fromJson;
@override
bool get multiple;
@override
bool get required;
@override
List<Type> get types;
@override
@JsonKey(ignore: true)
_$$_FieldCopyWith<_$_Field> get copyWith =>
throw _privateConstructorUsedError;
}

@ -1,46 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'gen_grammar.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_$_Type _$$_TypeFromJson(Map<String, dynamic> json) => _$_Type(
type: json['type'] as String,
named: json['named'] as bool,
fields: (json['fields'] as Map<String, dynamic>?)?.map(
(k, e) => MapEntry(k, Field.fromJson(e as Map<String, dynamic>)),
) ??
const {},
children: json['children'] == null
? null
: Field.fromJson(json['children'] as Map<String, dynamic>),
subtypes: (json['subtypes'] as List<dynamic>?)
?.map((e) => Type.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
);
Map<String, dynamic> _$$_TypeToJson(_$_Type instance) => <String, dynamic>{
'type': instance.type,
'named': instance.named,
'fields': instance.fields,
'children': instance.children,
'subtypes': instance.subtypes,
};
_$_Field _$$_FieldFromJson(Map<String, dynamic> json) => _$_Field(
multiple: json['multiple'] as bool,
required: json['required'] as bool,
types: (json['types'] as List<dynamic>?)
?.map((e) => Type.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
);
Map<String, dynamic> _$$_FieldToJson(_$_Field instance) => <String, dynamic>{
'multiple': instance.multiple,
'required': instance.required,
'types': instance.types,
};

@ -1,14 +0,0 @@
import 'dart:io';
import 'package:dylib/dylib.dart';
import 'package:tree_sitter/tree_sitter.dart';
void main() {
final parser = Parser(
sharedLibrary: resolveDylibPath('dart', path: Directory.current.path),
entryPoint: 'tree_sitter_dart');
final program = "class A {}";
final tree = parser.parse(program);
print(tree.root.child(0).namedChild(0).string);
print(parser.getText(tree.root.child(0).namedChild(0)));
}

@ -1,243 +0,0 @@
// AUTO GENERATED FILE, DO NOT EDIT.
//
// Generated by `package:ffigen`.
// ignore_for_file: type=lint
import 'dart:ffi' as ffi;
final class TSLanguage extends ffi.Struct {
@ffi.Uint32()
external int version;
@ffi.Uint32()
external int symbol_count;
@ffi.Uint32()
external int alias_count;
@ffi.Uint32()
external int token_count;
@ffi.Uint32()
external int external_token_count;
@ffi.Uint32()
external int state_count;
@ffi.Uint32()
external int large_state_count;
@ffi.Uint32()
external int production_id_count;
@ffi.Uint32()
external int field_count;
@ffi.Uint16()
external int max_alias_sequence_length;
external ffi.Pointer<ffi.Uint16> parse_table;
external ffi.Pointer<ffi.Uint16> small_parse_table;
external ffi.Pointer<ffi.Uint32> small_parse_table_map;
external ffi.Pointer<TSParseActionEntry> parse_actions;
external ffi.Pointer<ffi.Pointer<ffi.Char>> symbol_names;
external ffi.Pointer<ffi.Pointer<ffi.Char>> field_names;
external ffi.Pointer<TSFieldMapSlice> field_map_slices;
external ffi.Pointer<TSFieldMapEntry> field_map_entries;
external ffi.Pointer<TSSymbolMetadata> symbol_metadata;
external ffi.Pointer<TSSymbol> public_symbol_map;
external ffi.Pointer<ffi.Uint16> alias_map;
external ffi.Pointer<TSSymbol> alias_sequences;
external ffi.Pointer<TSLexMode> lex_modes;
external ffi.Pointer<
ffi.NativeFunction<
ffi.Bool Function(ffi.Pointer<TSLexer>, TSStateId)>> lex_fn;
external ffi.Pointer<
ffi.NativeFunction<
ffi.Bool Function(ffi.Pointer<TSLexer>, TSStateId)>> keyword_lex_fn;
@TSSymbol()
external int keyword_capture_token;
external UnnamedStruct4 external_scanner;
external ffi.Pointer<TSStateId> primary_state_ids;
}
final class TSParseActionEntry extends ffi.Union {
external TSParseAction action;
external UnnamedStruct3 entry;
}
final class TSParseAction extends ffi.Union {
external UnnamedStruct1 shift;
external UnnamedStruct2 reduce;
@ffi.Uint8()
external int type;
}
final class UnnamedStruct1 extends ffi.Struct {
@ffi.Uint8()
external int type;
@TSStateId()
external int state;
@ffi.Bool()
external bool extra;
@ffi.Bool()
external bool repetition;
}
typedef TSStateId = ffi.Uint16;
final class UnnamedStruct2 extends ffi.Struct {
@ffi.Uint8()
external int type;
@ffi.Uint8()
external int child_count;
@TSSymbol()
external int symbol;
@ffi.Int16()
external int dynamic_precedence;
@ffi.Uint16()
external int production_id;
}
typedef TSSymbol = ffi.Uint16;
final class UnnamedStruct3 extends ffi.Struct {
@ffi.Uint8()
external int count;
@ffi.Bool()
external bool reusable;
}
final class TSFieldMapSlice extends ffi.Struct {
@ffi.Uint16()
external int index;
@ffi.Uint16()
external int length;
}
final class TSFieldMapEntry extends ffi.Struct {
@TSFieldId()
external int field_id;
@ffi.Uint8()
external int child_index;
@ffi.Bool()
external bool inherited;
}
typedef TSFieldId = ffi.Uint16;
final class TSSymbolMetadata extends ffi.Struct {
@ffi.Bool()
external bool visible;
@ffi.Bool()
external bool named;
@ffi.Bool()
external bool supertype;
}
final class TSLexMode extends ffi.Struct {
@ffi.Uint16()
external int lex_state;
@ffi.Uint16()
external int external_lex_state;
}
final class TSLexer extends ffi.Struct {
@ffi.Int32()
external int lookahead;
@TSSymbol()
external int result_symbol;
external ffi.Pointer<
ffi.NativeFunction<ffi.Void Function(ffi.Pointer<TSLexer>, ffi.Bool)>>
advance;
external ffi
.Pointer<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<TSLexer>)>>
mark_end;
external ffi.Pointer<
ffi.NativeFunction<ffi.Uint32 Function(ffi.Pointer<TSLexer>)>> get_column;
external ffi
.Pointer<ffi.NativeFunction<ffi.Bool Function(ffi.Pointer<TSLexer>)>>
is_at_included_range_start;
external ffi
.Pointer<ffi.NativeFunction<ffi.Bool Function(ffi.Pointer<TSLexer>)>> eof;
}
final class UnnamedStruct4 extends ffi.Struct {
external ffi.Pointer<ffi.Bool> states;
external ffi.Pointer<TSSymbol> symbol_map;
external ffi.Pointer<ffi.NativeFunction<ffi.Pointer<ffi.Void> Function()>>
create;
external ffi
.Pointer<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Void>)>>
destroy;
external ffi.Pointer<
ffi.NativeFunction<
ffi.Bool Function(ffi.Pointer<ffi.Void>, ffi.Pointer<TSLexer>,
ffi.Pointer<ffi.Bool>)>> scan;
external ffi.Pointer<
ffi.NativeFunction<
ffi.UnsignedInt Function(
ffi.Pointer<ffi.Void>, ffi.Pointer<ffi.Char>)>> serialize;
external ffi.Pointer<
ffi.NativeFunction<
ffi.Void Function(ffi.Pointer<ffi.Void>, ffi.Pointer<ffi.Char>,
ffi.UnsignedInt)>> deserialize;
}
abstract class TSParseActionType {
static const int TSParseActionTypeShift = 0;
static const int TSParseActionTypeReduce = 1;
static const int TSParseActionTypeAccept = 2;
static const int TSParseActionTypeRecover = 3;
}
const int ts_builtin_sym_error = 65535;
const int ts_builtin_sym_end = 0;
const int TREE_SITTER_SERIALIZATION_BUFFER_SIZE = 1024;

@ -1,12 +0,0 @@
import 'dart:ffi';
import 'dart:io';
final DynamicLibrary stdlib = Platform.isWindows
? DynamicLibrary.open('ole32.dll')
: DynamicLibrary.process();
typedef PosixFreeNative = NativeFunction<Void Function(Pointer)>;
final posixFree = stdlib.lookup<PosixFreeNative>('free');
typedef WinCoTaskMemFreeNative = NativeFunction<Void Function(Pointer pv)>;
final winCoTaskMemFree = stdlib.lookup<WinCoTaskMemFreeNative>('CoTaskMemFree');
final free = Platform.isWindows ? winCoTaskMemFree : posixFree;

@ -1,305 +0,0 @@
/// A tree sitter parsing library for Dart.
// ignore_for_file: unused_element
library;
import 'dart:convert';
import 'dart:ffi';
import 'dart:ffi' as ffi;
import 'dart:io';
import 'package:dylib/dylib.dart';
import 'package:ffi/ffi.dart';
import 'package:tree_sitter/tree_sitter.dart';
import 'src/parser_generated_bindings.dart' as details;
import 'src/utils.dart';
export 'src/generated_bindings.dart';
/// Exposes the tree sitter C API as a minimal dart ffi wrapper
final treeSitterApi = TreeSitterConfig.instance.ffiApi;
/// Configuration of the package to find the correct shared libraries
final class TreeSitterConfig {
static String _dylibLocation =
resolveDylibPath('tree-sitter', path: Directory.current.path);
late final ffiApi = TreeSitter(DynamicLibrary.open(_dylibLocation));
/// Sets the path to find the tree sitter shared libraries
static void setLibraryPath(String path) {
_dylibLocation = path;
}
TreeSitterConfig._();
static final instance = TreeSitterConfig._();
}
/// A dart interface to the tree sitter API
///
/// - Handles basic parser / language setup
base class Parser implements Finalizable {
/// The shared library for the language used by this parser
final String sharedLibrary;
/// The entry point for the language used by this parser
final String entryPoint;
/// The c ffi parser instance
///
/// Automatically disposed by [Parser] using dart's Finalizable support
late final parser = treeSitterApi.ts_parser_new();
late final _langDylib = DynamicLibrary.open(sharedLibrary);
late final _languagePtr =
_langDylib.lookup<ffi.NativeFunction<ffi.Pointer<TSLanguage> Function()>>(
entryPoint);
late final _language =
_languagePtr.asFunction<ffi.Pointer<TSLanguage> Function()>()();
final _finalizer =
NativeFinalizer(treeSitterApi.addresses.ts_parser_delete.cast());
/// Creates a new parser with the given shared library and entry point
///
/// Sets up a language for the parser to use based on those parameters
Parser({required this.sharedLibrary, required this.entryPoint}) {
_finalizer.attach(this, parser.cast(), detach: this);
if (!treeSitterApi.ts_parser_set_language(parser, _language)) {
throw Exception(
'Failed to set language using the provided shared library and entry point');
}
}
details.TSLanguage get language => _language.cast<details.TSLanguage>().ref;
/// Parses out a tree from the given string
Tree parse(String program, {int? encoding}) {
_contents = program;
final pProgram = program.toNativeUtf8().cast<Char>();
if (encoding == null) {
return Tree(treeSitterApi.ts_parser_parse_string(
parser, nullptr, pProgram, program.length));
} else {
return Tree(treeSitterApi.ts_parser_parse_string_encoding(
parser, nullptr, pProgram, program.length, encoding));
}
}
String? _contents;
List<int> get contents => utf8.encode(_contents ?? '');
void reset() => treeSitterApi.ts_parser_reset(parser);
set timeoutMicros(int timeout) =>
treeSitterApi.ts_parser_set_timeout_micros(parser, timeout);
int get timeoutMicros => treeSitterApi.ts_parser_timeout_micros(parser);
set cancellationFlag(CancelToken flag) =>
treeSitterApi.ts_parser_set_cancellation_flag(parser, flag._token);
CancelToken get cancellationFlag =>
CancelToken.fromToken(treeSitterApi.ts_parser_cancellation_flag(parser));
String getText(TSNode namedChild) {
final text = contents.sublist(namedChild.startByte, namedChild.endByte);
return utf8.decode(text);
}
}
final class CancelToken implements Finalizable {
final Pointer<Size> _token;
final _finalizer = NativeFinalizer(free.cast());
CancelToken() : _token = calloc<Size>(1) {
_finalizer.attach(this, _token.cast(), detach: this);
}
CancelToken.fromToken(this._token) {
_finalizer.attach(this, _token.cast(), detach: this);
}
void cancel() => _token.value = 1;
}
base class Tree implements Finalizable {
final Pointer<TSTree> tree;
final _finalizer =
NativeFinalizer(treeSitterApi.addresses.ts_tree_delete.cast());
Tree(this.tree) {
if (tree == nullptr) {
throw Exception('Tree is null');
}
_finalizer.attach(this, tree.cast(), detach: this);
}
TSNode get root => treeSitterApi.ts_tree_root_node(tree);
Tree get copy => Tree(treeSitterApi.ts_tree_copy(tree));
details.TSLanguage get language =>
treeSitterApi.ts_tree_language(tree).cast<details.TSLanguage>().ref;
}
base class TreeCursor implements Finalizable {
late final Pointer<TSTreeCursor> cursor = malloc<TSTreeCursor>(1);
final _finalizer =
NativeFinalizer(treeSitterApi.addresses.ts_tree_cursor_delete.cast());
final TSNode node;
TreeCursor(this.node) {
cursor.ref = treeSitterApi.ts_tree_cursor_new(node);
_finalizer.attach(this, cursor.cast(), detach: this);
}
}
base class Query implements Finalizable {
late final Pointer<TSQuery> query;
final _finalizer =
NativeFinalizer(treeSitterApi.addresses.ts_query_delete.cast());
Query(this.query) {
_finalizer.attach(this, query.cast(), detach: this);
}
Query.fromSource(
{required Pointer<TSLanguage> language, required String source}) {
final pSource = source.toNativeUtf8().cast<Char>();
final length = utf8.encode(source).length;
using((alloc) {
final errorOffset = alloc<Uint32>(1);
final errorType = alloc<Int32>(1);
query = treeSitterApi.ts_query_new(
language, pSource, length, errorOffset, errorType);
if (query == nullptr) {
final errOff = errorOffset.value;
final errType = errorType.value;
throw Exception(
'Failed to create query from source "$source" ${errType.queryError} at offset $errOff]}');
}
});
}
}
extension TSApiIntX on int {
String get queryError => switch (this) {
TSQueryError.TSQueryErrorNone => 'TSQueryErrorNone',
TSQueryError.TSQueryErrorSyntax => 'TSQueryErrorSyntax',
TSQueryError.TSQueryErrorNodeType => 'TSQueryErrorNodeType',
TSQueryError.TSQueryErrorField => 'TSQueryErrorField',
TSQueryError.TSQueryErrorCapture => 'TSQueryErrorCapture',
TSQueryError.TSQueryErrorStructure => 'TSQueryErrorStructure',
TSQueryError.TSQueryErrorLanguage => 'TSQueryErrorLanguage',
_ => 'Unknown error code $this'
};
String get queryPredicateStepType => switch (this) {
TSQueryPredicateStepType.TSQueryPredicateStepTypeCapture =>
'TSQueryPredicateStepTypeCapture',
TSQueryPredicateStepType.TSQueryPredicateStepTypeString =>
'TSQueryPredicateStepTypeString',
TSQueryPredicateStepType.TSQueryPredicateStepTypeDone =>
'TSQueryPredicateStepTypeDone',
_ => 'Unknown predicate step type $this'
};
String get quantifier => switch (this) {
TSQuantifier.TSQuantifierZero => 'TSQuantifierZero',
TSQuantifier.TSQuantifierZeroOrOne => 'TSQuantifierZeroOrOne',
TSQuantifier.TSQuantifierZeroOrMore => 'TSQuantifierZeroOrMore',
TSQuantifier.TSQuantifierOne => 'TSQuantifierOne',
TSQuantifier.TSQuantifierOneOrMore => 'TSQuantifierOneOrMore',
_ => 'Unknown predicate step type $this'
};
String get symbolType => switch (this) {
TSSymbolType.TSSymbolTypeRegular => 'TSSymbolTypeRegular',
TSSymbolType.TSSymbolTypeAnonymous => 'TSSymbolTypeAnonymous',
TSSymbolType.TSSymbolTypeAuxiliary => 'TSSymbolTypeAuxiliary',
_ => 'Unknown symbol type $this'
};
String get inputEncoding => switch (this) {
TSInputEncoding.TSInputEncodingUTF8 => 'TSInputEncodingUTF8',
TSInputEncoding.TSInputEncodingUTF16 => 'TSInputEncodingUTF16',
_ => 'Unknown input encoding $this'
};
String get logType => switch (this) {
TSLogType.TSLogTypeParse => 'TSLogTypeParse',
TSLogType.TSLogTypeLex => 'TSLogTypeLex',
_ => 'Unknown log type $this'
};
}
base class QueryCursor implements Finalizable {
final Pointer<TSQueryCursor> cursor = treeSitterApi.ts_query_cursor_new();
final _finalizer =
NativeFinalizer(treeSitterApi.addresses.ts_query_delete.cast());
QueryCursor() {
_finalizer.attach(this, cursor.cast(), detach: this);
}
}
extension TSNodeX on TSNode {
String get string {
final root = treeSitterApi.ts_node_string(this);
final result = root.cast<Utf8>().toDartString();
malloc.free(root);
return result;
}
String get nodeType =>
treeSitterApi.ts_node_type(this).cast<Utf8>().toDartString();
int get symbol => treeSitterApi.ts_node_symbol(this);
int get startByte => treeSitterApi.ts_node_start_byte(this);
int get endByte => treeSitterApi.ts_node_end_byte(this);
TSPoint get startPoint => treeSitterApi.ts_node_start_point(this);
TSPoint get endPoint => treeSitterApi.ts_node_end_point(this);
bool get isNull => treeSitterApi.ts_node_is_null(this);
bool get isNamed => treeSitterApi.ts_node_is_named(this);
bool get isMissing => treeSitterApi.ts_node_is_missing(this);
bool get isExtra => treeSitterApi.ts_node_is_extra(this);
bool get hasChanges => treeSitterApi.ts_node_has_changes(this);
bool get hasError => treeSitterApi.ts_node_has_error(this);
TSNode get parent => treeSitterApi.ts_node_parent(this);
TSNode child(int childIndex) => treeSitterApi.ts_node_child(this, childIndex);
String fieldNameForChild(int childIndex) => treeSitterApi
.ts_node_field_name_for_child(this, childIndex)
.cast<Utf8>()
.toDartString();
int get childCount => treeSitterApi.ts_node_child_count(this);
TSNode namedChild(int childIndex) =>
treeSitterApi.ts_node_named_child(this, childIndex);
int get namedChildCount => treeSitterApi.ts_node_named_child_count(this);
TSNode childByFieldName(String fieldName, int fieldNameLength) {
final pFieldName = fieldName.toNativeUtf8().cast<Char>();
final result = treeSitterApi.ts_node_child_by_field_name(
this, pFieldName, fieldNameLength);
malloc.free(pFieldName);
return result;
}
TSNode childByFieldId(int fieldId) =>
treeSitterApi.ts_node_child_by_field_id(this, fieldId);
TSNode get nextSibling => treeSitterApi.ts_node_next_sibling(this);
TSNode get prevSibling => treeSitterApi.ts_node_prev_sibling(this);
TSNode get nextNamedSibling => treeSitterApi.ts_node_next_named_sibling(this);
TSNode get prevNamedSibling => treeSitterApi.ts_node_prev_named_sibling(this);
}

@ -1,8 +0,0 @@
name: "TSParser"
description: "C Bindings to the TreeSitter Parser library"
output: 'lib/src/parser_generated_bindings.dart'
headers:
entry-points:
- 'tree-sitter/lib/include/tree_sitter/parser.h'
include-directives:
- 'tree-sitter/lib/include/tree_sitter/parser.h'

@ -1,26 +0,0 @@
name: tree_sitter
description: A tree sitter parsing library
version: 0.1.1
repository: https://github.com/UserNobody14/tree-sitter-dart
environment:
sdk: ">=3.0.0 <3.2.0"
dependencies:
dylib: ^0.3.3
args: ^2.4.1
ffi: ^2.0.1
freezed_annotation: ^2.2.0
path: ^1.8.3
json_annotation: ^4.8.1
dev_dependencies:
lints: ^2.1.0
test: ^1.24.2
ffigen: ^8.0.2
freezed: ^2.3.4
json_serializable: ^6.7.0
build_runner: ^2.4.4
executables:
tsdart: gen_grammar

@ -1,16 +0,0 @@
import 'dart:io';
import 'package:dylib/dylib.dart';
import 'package:test/test.dart';
import 'package:tree_sitter/tree_sitter.dart';
void main() {
test('calculate', () {
final parser = Parser(
sharedLibrary: resolveDylibPath('dart', path: Directory.current.path),
entryPoint: 'tree_sitter_dart');
final program = "class A {}";
final tree = parser.parse(program);
print(tree.root.string);
});
}

@ -1 +0,0 @@
Subproject commit be79158f7ed916190524348bebef252dcfe15d44