Merge branch 'cmake'

pull/341/head
Wilfred Hughes 2022-08-20 18:36:07 +07:00
commit 515932151f
36 changed files with 23218 additions and 1 deletions

@ -2,6 +2,8 @@
### Parsing ### Parsing
Added support for CMake.
Improved comment detection using tree-sitter syntax highlighting Improved comment detection using tree-sitter syntax highlighting
queries. queries.

@ -88,6 +88,11 @@ fn main() {
src_dir: "vendor/tree-sitter-clojure-src", src_dir: "vendor/tree-sitter-clojure-src",
extra_files: vec![], extra_files: vec![],
}, },
TreeSitterParser {
name: "tree-sitter-cmake",
src_dir: "vendor/tree-sitter-cmake-src",
extra_files: vec!["scanner.cc"],
},
TreeSitterParser { TreeSitterParser {
name: "tree-sitter-commonlisp", name: "tree-sitter-commonlisp",
src_dir: "vendor/tree-sitter-commonlisp-src", src_dir: "vendor/tree-sitter-commonlisp-src",

@ -9,6 +9,7 @@ Difftastic supports the following programming languages.
| C++ | [tree-sitter/tree-sitter-cpp](https://github.com/tree-sitter/tree-sitter-cpp) | | C++ | [tree-sitter/tree-sitter-cpp](https://github.com/tree-sitter/tree-sitter-cpp) |
| C# | [tree-sitter/tree-sitter-c-sharp](https://github.com/tree-sitter/tree-sitter-c-sharp) | | C# | [tree-sitter/tree-sitter-c-sharp](https://github.com/tree-sitter/tree-sitter-c-sharp) |
| Clojure | [sogaiu/tree-sitter-clojure](https://github.com/sogaiu/tree-sitter-clojure) ([branched](https://github.com/sogaiu/tree-sitter-clojure/tree/issue-21)) | | Clojure | [sogaiu/tree-sitter-clojure](https://github.com/sogaiu/tree-sitter-clojure) ([branched](https://github.com/sogaiu/tree-sitter-clojure/tree/issue-21)) |
| 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 | [UserNobody14/tree-sitter-dart](https://github.com/UserNobody14/tree-sitter-dart) |
| 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) |

@ -67,7 +67,7 @@ fn prefer_outer_delimiter(language: guess_language::Language) -> bool {
// For everything else, prefer the inner delimiter. These // For everything else, prefer the inner delimiter. These
// languages have syntax like `foo(bar)` or `foo[bar]` where // languages have syntax like `foo(bar)` or `foo[bar]` where
// the inner delimiter is more relevant. // the inner delimiter is more relevant.
Bash | C | CPlusPlus | CSharp | Css | Dart | Elixir | Elm | Elvish | Gleam | Go | Hack Bash | C | CMake | CPlusPlus | CSharp | Css | Dart | Elixir | Elm | Elvish | Gleam | Go | Hack
| Haskell | Html | Java | JavaScript | Jsx | Julia | Kotlin | Lua | Nix | OCaml | Haskell | Html | Java | JavaScript | Jsx | Julia | Kotlin | Lua | Nix | OCaml
| OCamlInterface | Perl | Php | Python | Ruby | Rust | Scala | Swift | Tsx | TypeScript | OCamlInterface | Perl | Php | Python | Ruby | Rust | Scala | Swift | Tsx | TypeScript
| Yaml | Zig => false, | Yaml | Zig => false,

@ -21,6 +21,7 @@ pub enum Language {
Bash, Bash,
C, C,
Clojure, Clojure,
CMake,
CommonLisp, CommonLisp,
CPlusPlus, CPlusPlus,
CSharp, CSharp,
@ -196,6 +197,7 @@ fn from_name(path: &Path) -> Option<Language> {
| "PKGBUILD" | "bash_aliases" | "bash_logout" | "bash_profile" | "bashrc" | "cshrc" | "PKGBUILD" | "bash_aliases" | "bash_logout" | "bash_profile" | "bashrc" | "cshrc"
| "gradlew" | "kshrc" | "login" | "man" | "profile" | "zlogin" | "zlogout" | "gradlew" | "kshrc" | "login" | "man" | "profile" | "zlogin" | "zlogout"
| "zprofile" | "zshenv" | "zshrc" => Some(Bash), | "zprofile" | "zshenv" | "zshrc" => Some(Bash),
"CMakeLists.txt" => Some(CMake),
".emacs" | "_emacs" | "Cask" => Some(EmacsLisp), ".emacs" | "_emacs" | "Cask" => Some(EmacsLisp),
".arcconfig" | ".auto-changelog" | ".c8rc" | ".htmlhintrc" | ".imgbotconfig" ".arcconfig" | ".auto-changelog" | ".c8rc" | ".htmlhintrc" | ".imgbotconfig"
| ".nycrc" | ".tern-config" | ".tern-project" | ".watchmanconfig" | "Pipfile.lock" | ".nycrc" | ".tern-config" | ".tern-project" | ".watchmanconfig" | "Pipfile.lock"
@ -222,6 +224,7 @@ pub fn from_extension(extension: &OsStr) -> Option<Language> {
Some(Clojure) Some(Clojure)
} }
"lisp" | "lsp" | "asd" => Some(CommonLisp), "lisp" | "lsp" | "asd" => Some(CommonLisp),
"cmake" | "cmake.in" => Some(CMake),
"cs" => Some(CSharp), "cs" => Some(CSharp),
"css" => Some(Css), "css" => Some(Css),
"dart" => Some(Dart), "dart" => Some(Dart),

@ -47,6 +47,7 @@ extern "C" {
fn tree_sitter_c() -> ts::Language; fn tree_sitter_c() -> ts::Language;
fn tree_sitter_c_sharp() -> ts::Language; fn tree_sitter_c_sharp() -> ts::Language;
fn tree_sitter_clojure() -> ts::Language; fn tree_sitter_clojure() -> ts::Language;
fn tree_sitter_cmake() -> ts::Language;
fn tree_sitter_cpp() -> ts::Language; fn tree_sitter_cpp() -> ts::Language;
fn tree_sitter_commonlisp() -> ts::Language; fn tree_sitter_commonlisp() -> ts::Language;
fn tree_sitter_css() -> ts::Language; fn tree_sitter_css() -> ts::Language;
@ -164,6 +165,20 @@ pub fn from_language(language: guess::Language) -> TreeSitterConfig {
.unwrap(), .unwrap(),
} }
} }
CMake => {
let language = unsafe { tree_sitter_cmake() };
TreeSitterConfig {
name: "CMake",
language,
atom_nodes: vec!["argument"].into_iter().collect(),
delimiter_tokens: vec![("(", ")")].into_iter().collect(),
highlight_query: ts::Query::new(
language,
include_str!("../../vendor/highlights/cmake.scm"),
)
.unwrap(),
}
}
CommonLisp => { CommonLisp => {
let language = unsafe { tree_sitter_commonlisp() }; let language = unsafe { tree_sitter_commonlisp() };
TreeSitterConfig { TreeSitterConfig {

@ -0,0 +1,128 @@
;; Based on the nvim-treesitter highlighting, which is under the Apache license.
;; https://github.com/nvim-treesitter/nvim-treesitter/blob/d76b0de6536c2461f97cfeca0550f8cb89793935/queries/cmake/highlights.scm
[
(quoted_argument)
(bracket_argument)
] @string
(variable_ref) @none
(variable) @variable
[
(bracket_comment)
(line_comment)
] @comment
(normal_command (identifier) @function)
["ENV" "CACHE"] @symbol
["$" "{" "}" "<" ">"] @punctuation.special
["(" ")"] @punctuation.bracket
[
(function)
(endfunction)
(macro)
(endmacro)
] @keyword.function
[
(if)
(elseif)
(else)
(endif)
] @conditional
[
(foreach)
(endforeach)
(while)
(endwhile)
] @repeat
(function_command
(function)
. (argument) @function
(argument)* @parameter
)
(macro_command
(macro)
. (argument) @function.macro
(argument)* @parameter
)
;; (normal_command
;; (identifier) @function.builtin
;; . (argument) @variable
;; (#match? @function.builtin "\\c^(set)$")
;; )
;; (normal_command
;; (identifier) @function.builtin
;; (#match? @function.builtin "\\c^(set)$")
;; (
;; (argument) @constant
;; (#any-of? @constant "PARENT_SCOPE")
;; ) .
;; )
;; (normal_command
;; (identifier) @function.builtin
;; (#match? @function.builtin "\\c^(set)$")
;; . (argument)
;; (
;; (argument) @_cache @constant
;; .
;; (argument) @_type @constant
;; (#any-of? @_cache "CACHE")
;; (#any-of? @_type "BOOL" "FILEPATH" "PATH" "STRING" "INTERNAL")
;; )
;; )
;; (normal_command
;; (identifier) @function.builtin
;; (#match? @function.builtin "\\c^(set)$")
;; . (argument)
;; (argument) @_cache
;; (#any-of? @_cache "CACHE")
;; (
;; (argument) @_force @constant
;; (#any-of? @_force "FORCE")
;; ) .
;; )
;; ((argument) @boolean
;; (#match? @boolean "\\c^(1|on|yes|true|y|0|off|no|false|n|ignore|notfound|.*-notfound)$")
;; )
(if_command
(if)
(argument) @keyword.operator
(#any-of? @keyword.operator "NOT" "AND" "OR"
"COMMAND" "POLICY" "TARGET" "TEST" "DEFINED" "IN_LIST"
"EXISTS" "IS_NEWER_THAN" "IS_DIRECTORY" "IS_SYMLINK" "IS_ABSOLUTE"
"MATCHES"
"LESS" "GREATER" "EQUAL" "LESS_EQUAL" "GREATER_EQUAL"
"STRLESS" "STRGREATER" "STREQUAL" "STRLESS_EQUAL" "STRGREATER_EQUAL"
"VERSION_LESS" "VERSION_GREATER" "VERSION_EQUAL" "VERSION_LESS_EQUAL" "VERSION_GREATER_EQUAL"
)
)
;; (normal_command
;; (identifier) @function.builtin
;; . (argument)
;; (argument) @constant
;; (#any-of? @constant "ALL" "COMMAND" "DEPENDS" "BYPRODUCTS" "WORKING_DIRECTORY" "COMMENT"
;; "JOB_POOL" "VERBATIM" "USES_TERMINAL" "COMMAND_EXPAND_LISTS" "SOURCES")
;; (#match? @function.builtin "\\c^(add_custom_target)$")
;; )
;; (normal_command
;; (identifier) @function.builtin
;; (argument) @constant
;; (#any-of? @constant "OUTPUT" "COMMAND" "MAIN_DEPENDENCY" "DEPENDS" "BYPRODUCTS" "IMPLICIT_DEPENDS" "WORKING_DIRECTORY"
;; "COMMENT" "DEPFILE" "JOB_POOL" "VERBATIM" "APPEND" "USES_TERMINAL" "COMMAND_EXPAND_LISTS")
;; (#match? @function.builtin "\\c^(add_custom_command)$")
;; )

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

@ -0,0 +1,129 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# Ignore lock file
package-lock.json
# Tree sitter generated files
parser.exp
parser.lib
parser.obj
scanner.obj
# Rust files
target/**
Cargo.lock

@ -0,0 +1 @@
printWidth = 120

@ -0,0 +1,26 @@
[package]
name = "tree-sitter-cmake"
description = "cmake grammar for the tree-sitter parsing library"
version = "0.1.0"
keywords = ["incremental", "parsing", "cmake"]
categories = ["parsing", "text-editors"]
repository = "https://github.com/uyha/tree-sitter-cmake"
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.20"
[build-dependencies]
cc = "1.0"

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2021 Uy Ha
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.

@ -0,0 +1,31 @@
==============================
A Tree-sitter parser for CMake
==============================
This project provides a `cmake` parser. Its primary use case is to provide a `cmake` parser for `nvim-treesitter`.
Parsed syntax
=============
- Command
- General commands
- For and while loops
- If conditions
- Functions and macros
- Arguments
- Quoted arguments
- Bracket arguments
- Unquoted arguments
- Parentheses
- Variable refences
- Environment and cache variables
- Normal variables
- Generator expression

@ -0,0 +1,19 @@
{
"targets": [
{
"target_name": "tree_sitter_CMake_binding",
"include_dirs": [
"<!(node -e \"require('nan')\")",
"src"
],
"sources": [
"bindings/node/binding.cc",
"src/parser.c",
# If your language uses an external scanner, add it here.
],
"cflags_c": [
"-std=c99",
]
}
]
}

@ -0,0 +1,28 @@
#include "tree_sitter/parser.h"
#include <node.h>
#include "nan.h"
using namespace v8;
extern "C" TSLanguage * tree_sitter_cmake();
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_cmake());
Nan::Set(instance, Nan::New("name").ToLocalChecked(), Nan::New("cmake").ToLocalChecked());
Nan::Set(module, Nan::New("exports").ToLocalChecked(), instance);
}
NODE_MODULE(tree_sitter_cmake_binding, Init)
} // namespace

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

@ -0,0 +1,38 @@
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());
}

@ -0,0 +1,52 @@
//! This crate provides cmake 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_cmake::language()).expect("Error loading cmake 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_cmake() -> 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_cmake() }
}
/// 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 cmake language");
}
}

@ -0,0 +1,93 @@
=========================================
Empty bracket argument [bracket_argument]
=========================================
message([[]])
---
(source_file
(normal_command
(identifier)
(argument (bracket_argument))
)
)
=======================================
One bracket argument [bracket_argument]
=======================================
message([[an argument]])
---
(source_file
(normal_command
(identifier)
(argument (bracket_argument))
)
)
========================================
Two bracket arguments [bracket_argument]
========================================
message([[first argument]] [[second argument]])
---
(source_file
(normal_command
(identifier)
(argument (bracket_argument))
(argument (bracket_argument))
)
)
========================================================
Two bracket with two equals arguments [bracket_argument]
========================================================
message(
[====[first argument]====]
[====[second argument]====]
)
---
(source_file
(normal_command
(identifier)
(argument (bracket_argument))
(argument (bracket_argument))
)
)
===================================================
Bracket argument with line break [bracket_argument]
===================================================
message([[an argument
with line break
]])
---
(source_file
(normal_command
(identifier)
(argument (bracket_argument))
)
)
=====================================================================================
Bracket argument with embedded brackets and equal signs line break [bracket_argument]
=====================================================================================
message([===[an argument
with line break ]==]
]===])
---
(source_file
(normal_command
(identifier)
(argument (bracket_argument))
)
)

@ -0,0 +1,58 @@
=========================
Bracket comment [comment]
=========================
#[[Some comment]]
---
(source_file
(bracket_comment)
)
==========================================================
Command invocation with embedded bracket comment [comment]
==========================================================
message(STATUS #[[Some comment]] "comment is next" #[[Some comment]])
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(bracket_comment)
(argument (quoted_argument (quoted_element)))
(bracket_comment)
)
)
======================
Line comment [comment]
======================
# [[Some comment]] "comment is next" #[[Some comment]]
---
(source_file
(line_comment)
)
===================================
Message with Line comment [comment]
===================================
message(STATUS #Some line comment
Second #Some other line comment
)
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(line_comment)
(argument (unquoted_argument))
(line_comment)
)
)

@ -0,0 +1,147 @@
====================
Empty if [condition]
====================
if ( cond )
endif()
---
(source_file
(if_condition
(if_command
(if)
(argument (unquoted_argument))
)
(endif_command (endif))
)
)
===========================
Empty if elseif [condition]
===========================
if(cond)
elseif(cond)
endif()
---
(source_file
(if_condition
(if_command
(if)
(argument (unquoted_argument))
)
(elseif_command
(elseif)
(argument (unquoted_argument))
)
(endif_command (endif))
)
)
================================
Empty if elseif else [condition]
================================
if(cond)
elseif(cond)
else()
endif()
---
(source_file
(if_condition
(if_command
(if)
(argument (unquoted_argument))
)
(elseif_command
(elseif)
(argument (unquoted_argument))
)
(else_command (else))
(endif_command (endif))
)
)
==========================================
If with one command invocation [condition]
==========================================
if(cond)
message(STATUS)
endif()
---
(source_file
(if_condition
(if_command
(if)
(argument (unquoted_argument))
)
(normal_command
(identifier)
(argument (unquoted_argument))
)
(endif_command (endif))
)
)
======================================
Condition with parentheses [condition]
======================================
if((A AND B) OR C)
endif()
---
(source_file
(if_condition
(if_command
(if)
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
)
(endif_command (endif))
)
)
==============================================
Condition with not and parentheses [condition]
==============================================
if(NOT (A AND B) OR C)
else(NOT (A AND B) OR C)
endif(NOT (A AND B) OR C)
---
(source_file
(if_condition
(if_command
(if)
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
)
(else_command
(else)
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
)
(endif_command
(endif)
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
)
)
)

@ -0,0 +1,117 @@
==================================
Empty foreach loop [foreach]
==================================
foreach(var)
endforeach()
---
(source_file
(foreach_loop
(foreach_command
(foreach)
(argument (unquoted_argument))
)
(endforeach_command (endforeach))
)
)
===============================================================
Empty foreach loop with one argument endforeach [foreach]
===============================================================
foreach(var)
endforeach(var)
---
(source_file
(foreach_loop
(foreach_command
(foreach)
(argument (unquoted_argument))
)
(endforeach_command
(endforeach)
(argument (unquoted_argument))
)
))
=================================
Uppercase foreach [foreach]
=================================
FOREACH(var)
ENDFOREACH()
---
(source_file
(foreach_loop
(foreach_command
(foreach)
(argument (unquoted_argument))
)
(endforeach_command (endforeach))
)
)
==================================
Mixed case foreach [foreach]
==================================
forEach(var)
endForEach()
---
(source_file
(foreach_loop
(foreach_command
(foreach)
(argument (unquoted_argument))
)
(endforeach_command (endforeach))
)
)
==================================
Empty IN [foreach]
==================================
foreach(var IN)
endforeach()
---
(source_file
(foreach_loop
(foreach_command
(foreach)
(argument (unquoted_argument))
(argument (unquoted_argument))
)
(endforeach_command (endforeach))
)
)
==================================
Empty RANGE [foreach]
==================================
foreach(var RANGE)
endforeach()
---
(source_file
(foreach_loop
(foreach_command
(foreach)
(argument (unquoted_argument))
(argument (unquoted_argument))
)
(endforeach_command (endforeach))
)
)

@ -0,0 +1,32 @@
===================================================
add_custom_target without new line [function_calls]
===================================================
add_custom_target(OUTPUT somefile)
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(argument (unquoted_argument))
)
)
================================================
add_custom_target with new line [function_calls]
================================================
add_custom_target(
OUTPUT somefile)
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(argument (unquoted_argument))
)
)

@ -0,0 +1,98 @@
=======================================
Unquoted generator expression [gen_exp]
=======================================
message($<>)
---
(source_file
(normal_command
(identifier)
(argument
(unquoted_argument
(gen_exp)))))
=====================================
Quoted generator expression [gen_exp]
=====================================
message("$<>")
---
(source_file
(normal_command
(identifier)
(argument
(quoted_argument
(quoted_element
(gen_exp))))))
=====================
No argument [gen_exp]
=====================
message($<ANGLE-R>)
---
(source_file
(normal_command
(identifier)
(argument
(unquoted_argument
(gen_exp
(argument
(unquoted_argument)))))))
============================================
No argument with superfluous colon [gen_exp]
============================================
message($<ANGLE-R:>)
---
(source_file
(normal_command
(identifier)
(argument
(unquoted_argument
(gen_exp
(argument
(unquoted_argument)))))))
======================
One argument [gen_exp]
======================
message($<BOOL:-NOTFOUND>)
---
(source_file
(normal_command
(identifier)
(argument
(unquoted_argument
(gen_exp
(argument
(unquoted_argument))
(argument
(unquoted_argument)))))))
=======================
Two arguments [gen_exp]
=======================
message($<AND:TRUE,FALSE>)
---
(source_file
(normal_command
(identifier)
(argument
(unquoted_argument
(gen_exp
(argument
(unquoted_argument))
(argument
(unquoted_argument))
(argument
(unquoted_argument)))))))

@ -0,0 +1,93 @@
=====================
No argument [message]
=====================
message()
---
(source_file
(normal_command
(identifier)
)
)
=================================
No argument with spaces [message]
=================================
message( )
---
(source_file
(normal_command
(identifier)
)
)
===============================================
Message without argument with newline [message]
===============================================
message(
)
---
(source_file
(normal_command
(identifier)
)
)
==================================================
Message with STATUS and bracket argument [message]
==================================================
message(STATUS [=[Some argument ]==] ]=] )
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(argument (bracket_argument))
)
)
==============================================================
Message with STATUS and bracket argument and newline [message]
==============================================================
message(STATUS
[=[Some argument
]==] ]=] )
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(argument (bracket_argument))
)
)
======================================================
Message with STATUS and an unquoted argument [message]
======================================================
message(STATUS argument)
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(argument (unquoted_argument))
)
)

@ -0,0 +1,52 @@
===================================================
Parentheses inside command invocation [parentheses]
===================================================
message(STATUS (TEST))
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(argument (unquoted_argument))
)
)
===========================================================
Missing parentheses inside command invocation [parentheses]
===========================================================
message(STATUS (TEST)
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(argument (unquoted_argument)) (MISSING ")")
)
)
==================================================================
Nested missing parentheses inside command invocation [parentheses]
==================================================================
message(STATUS ((TEST))
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(argument (unquoted_argument)) (MISSING ")")
)
)
===============================================
Many arguments inside parentheses [parentheses]
===============================================
message(STATUS (TEST SECOND_TEST))
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(argument (unquoted_argument))
(argument (unquoted_argument))
)
)

@ -0,0 +1,176 @@
===========================================
One empty quoted argument [quoted_argument]
===========================================
message("")
---
(source_file
(normal_command
(identifier)
(argument (quoted_argument))
)
)
=====================================
One quoted argument [quoted_argument]
=====================================
message("An argument")
---
(source_file
(normal_command
(identifier)
(argument (quoted_argument (quoted_element)))
)
)
======================================
Two quoted arguments [quoted_argument]
======================================
message("First argument" "Second argument")
---
(source_file
(normal_command
(identifier)
(argument (quoted_argument (quoted_element)))
(argument (quoted_argument (quoted_element)))
)
)
===================================================
A quoted argument with line break [quoted_argument]
===================================================
message("An argument
with line break")
---
(source_file
(normal_command
(identifier)
(argument (quoted_argument (quoted_element)))
)
)
========================================
One variable reference [quoted_argument]
========================================
message("${var}")
---
(source_file
(normal_command
(identifier)
(argument
(quoted_argument
(quoted_element
(variable_ref (normal_var (variable)))
)
)
)
)
)
=========================================
Two Variable references [quoted_argument]
=========================================
message("${var} ${var}")
---
(source_file
(normal_command
(identifier)
(argument
(quoted_argument
(quoted_element
(variable_ref (normal_var (variable)))
(variable_ref (normal_var (variable)))
)
)
)
)
)
======================================================================
Variable reference inside another variable reference [quoted_argument]
======================================================================
message("${var_${var}}")
---
(source_file
(normal_command
(identifier)
(argument
(quoted_argument
(quoted_element
(variable_ref (normal_var (variable (variable_ref (normal_var (variable))))))
)
)
)
)
)
======================================================================
Lookalike bracket comment inside quoted argument [quoted_argument]
======================================================================
message("${var_${var}} #[[comment]]")
---
(source_file
(normal_command
(identifier)
(argument
(quoted_argument
(quoted_element
(variable_ref (normal_var (variable (variable_ref (normal_var (variable))))))
)
)
)
)
)
======================================================================
Lookalike line comment inside quoted argument [quoted_argument]
======================================================================
message("${var_${var}} #comment")
---
(source_file
(normal_command
(identifier)
(argument
(quoted_argument
(quoted_element
(variable_ref (normal_var (variable (variable_ref (normal_var (variable))))))
)
)
)
)
)
===========================================================
Lookalike variable inside quoted argument [quoted_argument]
===========================================================
message("$var")
---
(source_file
(normal_command
(identifier)
(argument
(quoted_argument
(quoted_element)
)
)
)
)

@ -0,0 +1,119 @@
========================================================
Command invocation with one argument [unquoted_argument]
========================================================
message(STATUS)
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
)
)
=========================================================
Command invocation with two arguments [unquoted_argument]
=========================================================
message(STATUS Hello)
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
(argument (unquoted_argument))
)
)
===============================================================
Command invocations with leading seperation [unquoted_argument]
===============================================================
message( STATUS)
message(
STATUS)
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
)
(normal_command
(identifier)
(argument (unquoted_argument))
)
)
============================================================
Command invocations with escape sequence [unquoted_argument]
============================================================
message( STATUS)
message(
STATUS)
---
(source_file
(normal_command
(identifier)
(argument (unquoted_argument))
)
(normal_command
(identifier)
(argument (unquoted_argument))
)
)
========================================
Variable referencing [unquoted_argument]
========================================
message(${var_ref})
---
(source_file
(normal_command
(identifier)
(argument
(unquoted_argument
(variable_ref (normal_var (variable)))
)
)
)
)
====================================================================
Variable referencing inside variable referencing [unquoted_argument]
====================================================================
message(${var_${var_ref}})
---
(source_file
(normal_command
(identifier)
(argument
(unquoted_argument
(variable_ref (normal_var (variable (variable_ref (normal_var (variable))))))
)
)
)
)
===============================================================
Lookalike variable inside unquoted argument [unquoted_argument]
===============================================================
message($var)
---
(source_file
(normal_command
(identifier)
(argument
(unquoted_argument)
)
)
)

@ -0,0 +1,41 @@
===================
Empty while [while]
===================
while(cond)
endwhile()
---
(source_file
(while_loop
(while_command
(while)
(argument (unquoted_argument))
)
(endwhile_command (endwhile))
)
)
============================================
Empty while with argument in endwhile[while]
============================================
while(cond)
endwhile(cond)
---
(source_file
(while_loop
(while_command
(while)
(argument (unquoted_argument))
)
(endwhile_command
(endwhile)
(argument (unquoted_argument))
)
)
)

@ -0,0 +1,104 @@
commands = [
"if",
"elseif",
"else",
"endif",
"foreach",
"endforeach",
"while",
"endwhile",
"function",
"endfunction",
"macro",
"endmacro",
];
module.exports = grammar({
name: "cmake",
externals: ($) => [$.bracket_argument, $.bracket_comment, $.line_comment],
extras: (_) => [],
rules: {
source_file: ($) => repeat($._untrimmed_command_invocation),
escape_sequence: ($) => choice($._escape_identity, $._escape_encoded, $._escape_semicolon),
_escape_identity: (_) => /\\[^A-Za-z0-9;]/,
_escape_encoded: (_) => choice("\\t", "\\r", "\\n"),
_escape_semicolon: (_) => ";",
variable: ($) => prec.left(repeat1(choice(/[a-zA-Z0-9/_.+-]/, $.escape_sequence, $.variable_ref))),
variable_ref: ($) => choice($.normal_var, $.env_var, $.cache_var),
normal_var: ($) => seq("$", "{", $.variable, "}"),
env_var: ($) => seq("$", "ENV", "{", $.variable, "}"),
cache_var: ($) => seq("$", "CACHE", "{", $.variable, "}"),
gen_exp: ($) => seq("$", "<", optional($._gen_exp_content), ">"),
_gen_exp_content: ($) => seq($.argument, optional($._gen_exp_arguments)),
_gen_exp_arguments: ($) => seq(":", repeat(seq($.argument, optional(/[,;]/)))),
argument: ($) => choice($.bracket_argument, $.quoted_argument, $.unquoted_argument),
_untrimmed_argument: ($) => choice(/\s/, $.bracket_comment, $.line_comment, $.argument, $._paren_argument),
_paren_argument: ($) => seq("(", repeat($._untrimmed_argument), ")"),
quoted_argument: ($) => seq('"', optional($.quoted_element), '"'),
quoted_element: ($) => repeat1(choice($.variable_ref, $.gen_exp, $._quoted_text, $.escape_sequence)),
_quoted_text: ($) => prec.left(repeat1(choice('$', /[^\\"]/))),
unquoted_argument: ($) => prec.right(repeat1(choice($.variable_ref, $.gen_exp, $._unquoted_text, $.escape_sequence))),
_unquoted_text: ($) => prec.left(repeat1(choice('$', /[^()#"\\']/))),
if_command: ($) => command($.if, repeat($._untrimmed_argument)),
elseif_command: ($) => command($.elseif, repeat($._untrimmed_argument)),
else_command: ($) => command($.else, repeat($._untrimmed_argument)),
endif_command: ($) => command($.endif, repeat($._untrimmed_argument)),
if_condition: ($) =>
seq(
$.if_command,
repeat(choice($._untrimmed_command_invocation, $.elseif_command, $.else_command)),
$.endif_command
),
foreach_command: ($) => command($.foreach, repeat($._untrimmed_argument)),
endforeach_command: ($) => command($.endforeach, optional($.argument)),
foreach_loop: ($) => seq($.foreach_command, repeat($._untrimmed_command_invocation), $.endforeach_command),
while_command: ($) => command($.while, repeat($._untrimmed_argument)),
endwhile_command: ($) => command($.endwhile, optional(seq(/\s*/, $.argument, /\s*/))),
while_loop: ($) => seq($.while_command, repeat($._untrimmed_command_invocation), $.endwhile_command),
function_command: ($) => command($.function, repeat($._untrimmed_argument)),
endfunction_command: ($) => command($.endfunction, repeat($._untrimmed_argument)),
function_def: ($) => seq($.function_command, repeat($._untrimmed_command_invocation), $.endfunction_command),
macro_command: ($) => command($.macro, repeat($._untrimmed_argument)),
endmacro_command: ($) => command($.endmacro, repeat($._untrimmed_argument)),
macro_def: ($) => seq($.macro_command, repeat($._untrimmed_command_invocation), $.endmacro_command),
normal_command: ($) => command($.identifier, repeat($._untrimmed_argument)),
_command_invocation: ($) =>
choice($.normal_command, $.if_condition, $.foreach_loop, $.while_loop, $.function_def, $.macro_def),
_untrimmed_command_invocation: ($) => choice(/\s/, $.bracket_comment, $.line_comment, $._command_invocation),
...commandNames(...commands),
identifier: (_) => /[A-Za-z_][A-Za-z0-9_]*/,
integer: (_) => /[+-]*\d+/,
},
});
function iregex(s) {
return new RegExp(Array.from(s).reduce((acc, value) => acc + `[${value.toLowerCase()}${value.toUpperCase()}]`, ""));
}
function commandName(name) {
return { [name]: (_) => iregex(name) };
}
function commandNames(...names) {
return Object.assign({}, ...names.map(commandName));
}
function command(name_rule, arg_rule) {
return seq(name_rule, repeat(/[\t ]/), "(", arg_rule, ")");
}

@ -0,0 +1,23 @@
{
"name": "tree-sitter-cmake",
"version": "0.1.0",
"description": "CMake grammar for tree-sitter",
"main": "bindings/node",
"author": "Uy Ha",
"license": "MIT",
"dependencies": {
"nan": "^2.16.0"
},
"tree-sitter": [
{
"scope": "source.cmake",
"file-types": [
"cmake",
"CMakeLists.txt"
]
}
],
"devDependencies": {
"tree-sitter-cli": "^0.20.6"
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,954 @@
[
{
"type": "argument",
"named": true,
"fields": {},
"children": {
"multiple": false,
"required": true,
"types": [
{
"type": "bracket_argument",
"named": true
},
{
"type": "quoted_argument",
"named": true
},
{
"type": "unquoted_argument",
"named": true
}
]
}
},
{
"type": "cache_var",
"named": true,
"fields": {},
"children": {
"multiple": false,
"required": true,
"types": [
{
"type": "variable",
"named": true
}
]
}
},
{
"type": "else_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "else",
"named": true
},
{
"type": "line_comment",
"named": true
}
]
}
},
{
"type": "elseif_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "elseif",
"named": true
},
{
"type": "line_comment",
"named": true
}
]
}
},
{
"type": "endforeach_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "endforeach",
"named": true
}
]
}
},
{
"type": "endfunction_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "endfunction",
"named": true
},
{
"type": "line_comment",
"named": true
}
]
}
},
{
"type": "endif_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "endif",
"named": true
},
{
"type": "line_comment",
"named": true
}
]
}
},
{
"type": "endmacro_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "endmacro",
"named": true
},
{
"type": "line_comment",
"named": true
}
]
}
},
{
"type": "endwhile_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "endwhile",
"named": true
}
]
}
},
{
"type": "env_var",
"named": true,
"fields": {},
"children": {
"multiple": false,
"required": true,
"types": [
{
"type": "variable",
"named": true
}
]
}
},
{
"type": "escape_sequence",
"named": true,
"fields": {}
},
{
"type": "foreach_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "foreach",
"named": true
},
{
"type": "line_comment",
"named": true
}
]
}
},
{
"type": "foreach_loop",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "bracket_comment",
"named": true
},
{
"type": "endforeach_command",
"named": true
},
{
"type": "foreach_command",
"named": true
},
{
"type": "foreach_loop",
"named": true
},
{
"type": "function_def",
"named": true
},
{
"type": "if_condition",
"named": true
},
{
"type": "line_comment",
"named": true
},
{
"type": "macro_def",
"named": true
},
{
"type": "normal_command",
"named": true
},
{
"type": "while_loop",
"named": true
}
]
}
},
{
"type": "function_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "function",
"named": true
},
{
"type": "line_comment",
"named": true
}
]
}
},
{
"type": "function_def",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "bracket_comment",
"named": true
},
{
"type": "endfunction_command",
"named": true
},
{
"type": "foreach_loop",
"named": true
},
{
"type": "function_command",
"named": true
},
{
"type": "function_def",
"named": true
},
{
"type": "if_condition",
"named": true
},
{
"type": "line_comment",
"named": true
},
{
"type": "macro_def",
"named": true
},
{
"type": "normal_command",
"named": true
},
{
"type": "while_loop",
"named": true
}
]
}
},
{
"type": "gen_exp",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": false,
"types": [
{
"type": "argument",
"named": true
}
]
}
},
{
"type": "if_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "if",
"named": true
},
{
"type": "line_comment",
"named": true
}
]
}
},
{
"type": "if_condition",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "bracket_comment",
"named": true
},
{
"type": "else_command",
"named": true
},
{
"type": "elseif_command",
"named": true
},
{
"type": "endif_command",
"named": true
},
{
"type": "foreach_loop",
"named": true
},
{
"type": "function_def",
"named": true
},
{
"type": "if_command",
"named": true
},
{
"type": "if_condition",
"named": true
},
{
"type": "line_comment",
"named": true
},
{
"type": "macro_def",
"named": true
},
{
"type": "normal_command",
"named": true
},
{
"type": "while_loop",
"named": true
}
]
}
},
{
"type": "macro_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "line_comment",
"named": true
},
{
"type": "macro",
"named": true
}
]
}
},
{
"type": "macro_def",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "bracket_comment",
"named": true
},
{
"type": "endmacro_command",
"named": true
},
{
"type": "foreach_loop",
"named": true
},
{
"type": "function_def",
"named": true
},
{
"type": "if_condition",
"named": true
},
{
"type": "line_comment",
"named": true
},
{
"type": "macro_command",
"named": true
},
{
"type": "macro_def",
"named": true
},
{
"type": "normal_command",
"named": true
},
{
"type": "while_loop",
"named": true
}
]
}
},
{
"type": "normal_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "identifier",
"named": true
},
{
"type": "line_comment",
"named": true
}
]
}
},
{
"type": "normal_var",
"named": true,
"fields": {},
"children": {
"multiple": false,
"required": true,
"types": [
{
"type": "variable",
"named": true
}
]
}
},
{
"type": "quoted_argument",
"named": true,
"fields": {},
"children": {
"multiple": false,
"required": false,
"types": [
{
"type": "quoted_element",
"named": true
}
]
}
},
{
"type": "quoted_element",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": false,
"types": [
{
"type": "escape_sequence",
"named": true
},
{
"type": "gen_exp",
"named": true
},
{
"type": "variable_ref",
"named": true
}
]
}
},
{
"type": "source_file",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": false,
"types": [
{
"type": "bracket_comment",
"named": true
},
{
"type": "foreach_loop",
"named": true
},
{
"type": "function_def",
"named": true
},
{
"type": "if_condition",
"named": true
},
{
"type": "line_comment",
"named": true
},
{
"type": "macro_def",
"named": true
},
{
"type": "normal_command",
"named": true
},
{
"type": "while_loop",
"named": true
}
]
}
},
{
"type": "unquoted_argument",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": false,
"types": [
{
"type": "escape_sequence",
"named": true
},
{
"type": "gen_exp",
"named": true
},
{
"type": "variable_ref",
"named": true
}
]
}
},
{
"type": "variable",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": false,
"types": [
{
"type": "escape_sequence",
"named": true
},
{
"type": "variable_ref",
"named": true
}
]
}
},
{
"type": "variable_ref",
"named": true,
"fields": {},
"children": {
"multiple": false,
"required": true,
"types": [
{
"type": "cache_var",
"named": true
},
{
"type": "env_var",
"named": true
},
{
"type": "normal_var",
"named": true
}
]
}
},
{
"type": "while_command",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "line_comment",
"named": true
},
{
"type": "while",
"named": true
}
]
}
},
{
"type": "while_loop",
"named": true,
"fields": {},
"children": {
"multiple": true,
"required": true,
"types": [
{
"type": "bracket_comment",
"named": true
},
{
"type": "endwhile_command",
"named": true
},
{
"type": "foreach_loop",
"named": true
},
{
"type": "function_def",
"named": true
},
{
"type": "if_condition",
"named": true
},
{
"type": "line_comment",
"named": true
},
{
"type": "macro_def",
"named": true
},
{
"type": "normal_command",
"named": true
},
{
"type": "while_command",
"named": true
},
{
"type": "while_loop",
"named": true
}
]
}
},
{
"type": "\"",
"named": false
},
{
"type": "$",
"named": false
},
{
"type": "(",
"named": false
},
{
"type": ")",
"named": false
},
{
"type": ":",
"named": false
},
{
"type": "<",
"named": false
},
{
"type": ">",
"named": false
},
{
"type": "CACHE",
"named": false
},
{
"type": "ENV",
"named": false
},
{
"type": "\\n",
"named": false
},
{
"type": "\\r",
"named": false
},
{
"type": "\\t",
"named": false
},
{
"type": "bracket_argument",
"named": true
},
{
"type": "bracket_comment",
"named": true
},
{
"type": "else",
"named": true
},
{
"type": "elseif",
"named": true
},
{
"type": "endforeach",
"named": true
},
{
"type": "endfunction",
"named": true
},
{
"type": "endif",
"named": true
},
{
"type": "endmacro",
"named": true
},
{
"type": "endwhile",
"named": true
},
{
"type": "foreach",
"named": true
},
{
"type": "function",
"named": true
},
{
"type": "identifier",
"named": true
},
{
"type": "if",
"named": true
},
{
"type": "line_comment",
"named": true
},
{
"type": "macro",
"named": true
},
{
"type": "while",
"named": true
},
{
"type": "{",
"named": false
},
{
"type": "}",
"named": false
}
]

File diff suppressed because it is too large Load Diff

@ -0,0 +1,90 @@
#include <cwctype>
#include <tree_sitter/parser.h>
namespace {
enum TokenType { BRACKET_ARGUMENT, BRACKET_COMMENT, LINE_COMMENT };
void skip(TSLexer *lexer) { lexer->advance(lexer, true); }
void advance(TSLexer *lexer) { lexer->advance(lexer, false); }
void skip_wspace(TSLexer *lexer) {
while (std::iswspace(lexer->lookahead)) {
skip(lexer);
}
}
bool is_bracket_argument(TSLexer *lexer) {
if (lexer->lookahead != '[') {
return false;
}
advance(lexer);
int open_level = 0;
while (lexer->lookahead == '=') {
++open_level;
advance(lexer);
}
if (lexer->lookahead != '[') {
return false;
}
while (lexer->lookahead != '\0') {
advance(lexer);
if (lexer->lookahead == ']') {
advance(lexer);
int close_level = 0;
while (lexer->lookahead == '=') {
++close_level;
advance(lexer);
}
if (lexer->lookahead == ']' && close_level == open_level) {
advance(lexer);
return true;
}
}
}
return false;
}
bool scan(void *payload, TSLexer *lexer, bool const *valid_symbols) {
skip_wspace(lexer);
if (lexer->lookahead != '#' && valid_symbols[BRACKET_ARGUMENT]) {
if (is_bracket_argument(lexer)) {
lexer->result_symbol = BRACKET_ARGUMENT;
return true;
}
}
if (lexer->lookahead == '#' &&
(valid_symbols[BRACKET_COMMENT] || valid_symbols[LINE_COMMENT])) {
advance(lexer);
if (is_bracket_argument(lexer)) {
lexer->result_symbol = BRACKET_COMMENT;
return true;
} else {
while (lexer->lookahead != '\n' && lexer->lookahead != '\0') {
advance(lexer);
}
lexer->result_symbol = LINE_COMMENT;
return true;
}
}
return false;
}
} // namespace
extern "C" {
void *tree_sitter_cmake_external_scanner_create() { return NULL; }
void tree_sitter_cmake_external_scanner_destroy(void *payload) {}
unsigned tree_sitter_cmake_external_scanner_serialize(void *payload,
char *buffer) {
return 0;
}
void tree_sitter_cmake_external_scanner_deserialize(void *payload,
char const *buffer,
unsigned length) {}
bool tree_sitter_cmake_external_scanner_scan(void *payload, TSLexer *lexer,
bool const *valid_symbols) {
return scan(payload, lexer, valid_symbols);
}
}

@ -0,0 +1,224 @@
#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_