Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Feat: Add C++ #368

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,9 @@
[submodule "resources/language-submodules/tree-sitter-php"]
path = resources/language-submodules/tree-sitter-php
url = https://github.com/tree-sitter/tree-sitter-php
[submodule "resources/language-submodules/tree-sitter-cpp"]
path = resources/language-submodules/tree-sitter-cpp
url = https://github.com/tree-sitter/tree-sitter-cpp
[submodule "resources/language-submodules/tree-sitter-c"]
path = resources/language-submodules/tree-sitter-c
url = https://github.com/tree-sitter/tree-sitter-c
22 changes: 16 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

51 changes: 51 additions & 0 deletions crates/core/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14987,3 +14987,54 @@ fn or_file() {
})
.unwrap();
}

#[test]
fn cpp_simple() {
run_test_expected({
TestArgExpected {
pattern: r#"
|language cpp
|`char* editor = $string_literal;` => `char* editor = "emacs";`
|"#
.trim_margin()
.unwrap(),
source: r#"char* editor = "vim";"#.to_owned(),
expected: r#"char* editor = "emacs";"#.to_owned(),
}
})
.unwrap();
}

#[test]
fn cpp_rename_variable_name() {
run_test_expected({
TestArgExpected {
pattern: r#"
|language cpp
|`char* $name = $val;` => `char* new_name = $val;`
|"#
.trim_margin()
.unwrap(),
source: r#"char* my_string = "hey";"#.to_owned(),
expected: r#"char* new_name = "hey";"#.to_owned(),
}
})
.unwrap();
}

#[test]
fn cpp_change_float_to_double() {
run_test_expected({
TestArgExpected {
pattern: r#"
|language cpp
|`int $foo` => `int what`
|"#
.trim_margin()
.unwrap(),
source: r#"int foo"#.to_owned(),
expected: r#"int foo"#.to_owned(),
}
})
.unwrap();
}
2 changes: 2 additions & 0 deletions crates/language/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ rust.unused_crate_dependencies = "warn"
[dependencies]
tree-sitter = { path = "../../vendor/tree-sitter-facade", package = "tree-sitter-facade-sg" }
tree-sitter-gritql = { path = "../../vendor/tree-sitter-gritql", optional = true }
tree-sitter-cpp = { path = "../../resources/language-metavariables/tree-sitter-cpp", optional = true }
tree-sitter-css = { path = "../../resources/language-metavariables/tree-sitter-css", optional = true }
tree-sitter-json = { path = "../../resources/language-metavariables/tree-sitter-json", optional = true }
tree-sitter-solidity = { path = "../../resources/language-metavariables/tree-sitter-solidity", optional = true }
Expand Down Expand Up @@ -64,6 +65,7 @@ builtin-parser = [
"tree-sitter-javascript",
"tree-sitter-html",
"tree-sitter-java",
"tree-sitter-cpp",
"tree-sitter-c-sharp",
"tree-sitter-python",
"tree-sitter-md",
Expand Down
105 changes: 105 additions & 0 deletions crates/language/src/cpp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use crate::language::{fields_for_nodes, Field, MarzanoLanguage, NodeTypes, SortId, TSLanguage};
use grit_util::Language;
use marzano_util::node_with_source::NodeWithSource;
use std::sync::OnceLock;

static NODE_TYPES_STRING: &str = include_str!("../../../resources/node-types/cpp-node-types.json");
static NODE_TYPES: OnceLock<Vec<Vec<Field>>> = OnceLock::new();
static LANGUAGE: OnceLock<TSLanguage> = OnceLock::new();

#[cfg(not(feature = "builtin-parser"))]
fn language() -> TSLanguage {
unimplemented!(
"tree-sitter parser must be initialized before use when [builtin-parser] is off."
)
}
#[cfg(feature = "builtin-parser")]
fn language() -> TSLanguage {
tree_sitter_cpp::language().into()
}

#[derive(Debug, Clone)]
pub struct Cpp {
node_types: &'static [Vec<Field>],
metavariable_sort: SortId,
comment_sort: SortId,
language: &'static TSLanguage,
}

impl Cpp {
pub(crate) fn new(lang: Option<TSLanguage>) -> Self {
let language = LANGUAGE.get_or_init(|| lang.unwrap_or_else(language));
let node_types = NODE_TYPES.get_or_init(|| fields_for_nodes(language, NODE_TYPES_STRING));
let metavariable_sort = language.id_for_node_kind("grit_metavariable", true);
let comment_sort = language.id_for_node_kind("comment", true);
Self {
node_types,
metavariable_sort,
comment_sort,
language,
}
}

pub(crate) fn is_initialized() -> bool {
LANGUAGE.get().is_some()
}
}

impl NodeTypes for Cpp {
fn node_types(&self) -> &[Vec<Field>] {
self.node_types
}
}

impl Language for Cpp {
use_marzano_delegate!();

fn language_name(&self) -> &'static str {
// TODO: Confirm C++ vs Cpp, etc. here.
"C++"
}

fn snippet_context_strings(&self) -> &[(&'static str, &'static str)] {
// TODO: Unclear about other good additions here. Presumably, there are many.
// TODO: Unclear if the following additions are good or bad.
&[
("", ""),
("", ";"),
("{", "}"),
("", " void GRIT_FN() {}"),
("void GRIT_FN(", "){}"),
("void GRIT_FN(){", "}"),
]
}
}

impl<'a> MarzanoLanguage<'a> for Cpp {
fn get_ts_language(&self) -> &TSLanguage {
self.language
}

fn is_comment_sort(&self, id: SortId) -> bool {
id == self.comment_sort
}

fn metavariable_sort(&self) -> SortId {
self.metavariable_sort
}
}

#[cfg(test)]
mod tests {

use crate::language::nodes_from_indices;

use super::*;

#[test]
fn snippet_nodes_not_empty() {
let snippet = r#"std::cout << "Hello World!";"#;
let lang = Cpp::new(None);
let snippets = lang.parse_snippet_contexts(snippet);
let nodes = nodes_from_indices(&snippets);
assert!(!nodes.is_empty());
}
}
1 change: 1 addition & 0 deletions crates/language/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ macro_rules! use_marzano_delegate {
};
}

pub mod cpp;
pub mod csharp;
pub mod css;
pub mod foreign_language;
Expand Down
2 changes: 2 additions & 0 deletions resources/edit_grammars.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ process.on('uncaughtException', (err) => {
///////////////////////////////////////////////////
const allLanguages = [
'c-sharp',
'c',
'cpp',
'css',
'go',
'hcl',
Expand Down
39 changes: 39 additions & 0 deletions resources/language-metavariables/tree-sitter-c/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.{json,toml,yml,gyp}]
indent_style = space
indent_size = 2

[*.js]
indent_style = space
indent_size = 2

[*.rs]
indent_style = space
indent_size = 4

[*.{c,cc,h}]
indent_style = space
indent_size = 4

[*.{py,pyi}]
indent_style = space
indent_size = 4

[*.swift]
indent_style = space
indent_size = 4

[*.go]
indent_style = tab
indent_size = 8

[Makefile]
indent_style = tab
indent_size = 8
11 changes: 11 additions & 0 deletions resources/language-metavariables/tree-sitter-c/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
* text eol=lf

src/*.json linguist-generated
src/parser.c linguist-generated
src/tree_sitter/* linguist-generated

bindings/** linguist-generated
binding.gyp linguist-generated
setup.py linguist-generated
Makefile linguist-generated
Package.swift linguist-generated
38 changes: 38 additions & 0 deletions resources/language-metavariables/tree-sitter-c/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Rust artifacts
Cargo.lock
target/

# Node artifacts
build/
prebuilds/
node_modules/
*.tgz

# Swift artifacts
.build/

# Go artifacts
go.sum
_obj/

# Python artifacts
.venv/
dist/
*.egg-info
*.whl

# C artifacts
*.a
*.so
*.so.*
*.dylib
*.dll
*.pc

# Example dirs
/examples/*/

# Grammar volatiles
*.wasm
*.obj
*.o
26 changes: 26 additions & 0 deletions resources/language-metavariables/tree-sitter-c/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "tree-sitter-c"
description = "C grammar for tree-sitter"
version = "0.21.4"
authors = [
"Max Brunsfeld <maxbrunsfeld@gmail.com>",
"Amaan Qureshi <amaanq12@gmail.com>",
]
license = "MIT"
keywords = ["incremental", "parsing", "tree-sitter", "c"]
categories = ["parsing", "text-editors"]
repository = "https://github.com/tree-sitter/tree-sitter-c"
edition = "2021"
autoexamples = false

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.90"
Loading