Skip to content

feat: complete c parser #13

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 28, 2025
Merged
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
3 changes: 3 additions & 0 deletions lang/collect/collect.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"strings"
"unicode"

"github.com/cloudwego/abcoder/lang/cxx"
"github.com/cloudwego/abcoder/lang/log"
. "github.com/cloudwego/abcoder/lang/lsp"
"github.com/cloudwego/abcoder/lang/rust"
Expand Down Expand Up @@ -79,6 +80,8 @@ func switchSpec(l uniast.Language) LanguageSpec {
switch l {
case uniast.Rust:
return &rust.RustSpec{}
case uniast.Cxx:
return &cxx.CxxSpec{}
default:
panic(fmt.Sprintf("unsupported language %s", l))
}
Expand Down
27 changes: 16 additions & 11 deletions lang/collect/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ func (c *Collector) fileLine(loc Location) uniast.FileLine {
}
}

func newModule(name string, dir string) *uniast.Module {
ret := uniast.NewModule(name, dir, uniast.Rust)
func newModule(name string, dir string, lang uniast.Language) *uniast.Module {
ret := uniast.NewModule(name, dir, lang)
return ret
}

Expand All @@ -67,7 +67,7 @@ func (c *Collector) Export(ctx context.Context) (*uniast.Repository, error) {
if err != nil {
return nil, err
}
repo.Modules[name] = newModule(name, rel)
repo.Modules[name] = newModule(name, rel, c.Language)
}

// not allow local symbols inside another symbol
Expand All @@ -83,11 +83,13 @@ func (c *Collector) Export(ctx context.Context) (*uniast.Repository, error) {
}

// patch module
for p, m := range repo.Modules {
if p == "" || strings.Contains(p, "@") {
continue
if c.modPatcher != nil {
for p, m := range repo.Modules {
if p == "" || strings.Contains(p, "@") {
continue
}
c.modPatcher.Patch(m)
}
c.modPatcher.Patch(m)
}

return &repo, nil
Expand Down Expand Up @@ -140,7 +142,7 @@ func (c *Collector) exportSymbol(repo *uniast.Repository, symbol *DocumentSymbol
}

if repo.Modules[mod] == nil {
repo.Modules[mod] = newModule(mod, "")
repo.Modules[mod] = newModule(mod, "", c.Language)
}
module := repo.Modules[mod]
if repo.Modules[mod].Packages[path] == nil {
Expand Down Expand Up @@ -284,7 +286,7 @@ func (c *Collector) exportSymbol(repo *uniast.Repository, symbol *DocumentSymbol
obj.GlobalVars = make([]uniast.Dependency, 0, len(deps))
}
obj.GlobalVars = uniast.InsertDependency(obj.GlobalVars, pdep)
case lsp.SKStruct, lsp.SKTypeParameter, lsp.SKInterface, lsp.SKEnum:
case lsp.SKStruct, lsp.SKTypeParameter, lsp.SKInterface, lsp.SKEnum, lsp.SKClass:
if obj.Types == nil {
obj.Types = make([]uniast.Dependency, 0, len(deps))
}
Expand All @@ -298,7 +300,7 @@ func (c *Collector) exportSymbol(repo *uniast.Repository, symbol *DocumentSymbol
pkg.Functions[id.Name] = obj

// Type
case lsp.SKStruct, lsp.SKTypeParameter, lsp.SKInterface, lsp.SKEnum:
case lsp.SKStruct, lsp.SKTypeParameter, lsp.SKInterface, lsp.SKEnum, lsp.SKClass:
obj := &uniast.Type{
FileLine: fileLine,
Content: content,
Expand All @@ -315,7 +317,7 @@ func (c *Collector) exportSymbol(repo *uniast.Repository, symbol *DocumentSymbol
continue
}
switch dep.Symbol.Kind {
case lsp.SKStruct, lsp.SKTypeParameter, lsp.SKInterface, lsp.SKEnum:
case lsp.SKStruct, lsp.SKTypeParameter, lsp.SKInterface, lsp.SKEnum, lsp.SKClass:
obj.SubStruct = append(obj.SubStruct, uniast.NewDependency(*depid, c.fileLine(dep.Location)))
default:
log.Error("dep symbol %s not collected for \n", dep.Symbol, id)
Expand Down Expand Up @@ -368,6 +370,9 @@ func mapKind(kind lsp.SymbolKind) uniast.TypeKind {
switch kind {
case lsp.SKStruct:
return "struct"
// XXX: C++ should use class instead of struct
case lsp.SKClass:
return "struct"
case lsp.SKTypeParameter:
return "type-parameter"
case lsp.SKInterface:
Expand Down
41 changes: 41 additions & 0 deletions lang/cxx/lib.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright 2025 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cxx

import (
"time"

"github.com/cloudwego/abcoder/lang/uniast"
"github.com/cloudwego/abcoder/lang/utils"
)

const MaxWaitDuration = 5 * time.Minute

func GetDefaultLSP() (lang uniast.Language, name string) {
return uniast.Cxx, "clangd-18"
}

func CheckRepo(repo string) (string, time.Duration) {
openfile := ""
// TODO: check if the project compiles.

// NOTICE: wait for Rust projects based on code files
_, size := utils.CountFiles(repo, ".c", "build/")
wait := 2*time.Second + time.Second*time.Duration(size/1024)
if wait > MaxWaitDuration {
wait = MaxWaitDuration
}
return openfile, wait
}
199 changes: 199 additions & 0 deletions lang/cxx/spec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
// Copyright 2025 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cxx

import (
"fmt"
"path/filepath"
"strings"

lsp "github.com/cloudwego/abcoder/lang/lsp"
"github.com/cloudwego/abcoder/lang/utils"
)

type CxxSpec struct {
repo string
}

func NewCxxSpec() *CxxSpec {
return &CxxSpec{}
}

// XXX: maybe multi module support for C++?
func (c *CxxSpec) WorkSpace(root string) (map[string]string, error) {
c.repo = root
rets := map[string]string{}
absPath, err := filepath.Abs(root)
if err != nil {
return nil, fmt.Errorf("failed to get absolute path: %w", err)
}
rets["current"] = absPath
return rets, nil
}

// returns: modname, pathpath, error
// Multiple symbols with the same name could occur (for example in the Linux kernel).
// The identify is mod::pkg::name. So we use the pkg (the file name) to distinguish them.
func (c *CxxSpec) NameSpace(path string) (string, string, error) {
// external lib: only standard library (system headers), in /usr/
if !strings.HasPrefix(path, c.repo) {
if strings.HasPrefix(path, "/usr") {
// assume it is c system library
return "cstdlib", "cstdlib", nil
}
panic(fmt.Sprintf("external lib: %s\n", path))
}

relpath, _ := filepath.Rel(c.repo, path)
return "current", relpath, nil
}

func (c *CxxSpec) ShouldSkip(path string) bool {
if strings.HasSuffix(path, ".c") || strings.HasSuffix(path, ".h") {
return false
}
return true
}

func (c *CxxSpec) IsDocToken(tok lsp.Token) bool {
return tok.Type == "comment"
}

func (c *CxxSpec) DeclareTokenOfSymbol(sym lsp.DocumentSymbol) int {
for i, t := range sym.Tokens {
if c.IsDocToken(t) {
continue
}
for _, m := range t.Modifiers {
if m == "declaration" {
return i
}
}
}
return -1
}

func (c *CxxSpec) IsEntityToken(tok lsp.Token) bool {
return tok.Type == "class" || tok.Type == "function" || tok.Type == "variable"
}

func (c *CxxSpec) IsStdToken(tok lsp.Token) bool {
panic("TODO")
}

func (c *CxxSpec) TokenKind(tok lsp.Token) lsp.SymbolKind {
switch tok.Type {
case "class":
return lsp.SKStruct
case "enum":
return lsp.SKEnum
case "enumMember":
return lsp.SKEnumMember
case "function", "macro":
return lsp.SKFunction
// rust spec does not treat parameter as a variable
case "parameter":
return lsp.SKVariable
case "typeParameter":
return lsp.SKTypeParameter
// type: TODO
case "interface", "concept", "method", "modifier", "namespace", "type":
panic(fmt.Sprintf("Unsupported token type: %s at %+v\n", tok.Type, tok.Location))
case "bracket", "comment", "label", "operator", "property", "unknown":
return lsp.SKUnknown
}
panic(fmt.Sprintf("Weird token type: %s at %+v\n", tok.Type, tok.Location))
}

func (c *CxxSpec) IsMainFunction(sym lsp.DocumentSymbol) bool {
return sym.Kind == lsp.SKFunction && sym.Name == "main"
}

func (c *CxxSpec) IsEntitySymbol(sym lsp.DocumentSymbol) bool {
typ := sym.Kind
return typ == lsp.SKFunction || typ == lsp.SKVariable || typ == lsp.SKClass

}

func (c *CxxSpec) IsPublicSymbol(sym lsp.DocumentSymbol) bool {
id := c.DeclareTokenOfSymbol(sym)
if id == -1 {
return false
}
for _, m := range sym.Tokens[id].Modifiers {
if m == "globalScope" {
return true
}
}
return false
}

// TODO(cpp): support C++ OOP
func (c *CxxSpec) HasImplSymbol() bool {
return false
}

func (c *CxxSpec) ImplSymbol(sym lsp.DocumentSymbol) (int, int, int) {
panic("TODO")
}

func (c *CxxSpec) FunctionSymbol(sym lsp.DocumentSymbol) (int, []int, []int, []int) {
// No receiver and no type params for C
if sym.Kind != lsp.SKFunction {
return -1, nil, nil, nil
}
receiver := -1
typeParams := []int{}
inputParams := []int{}
outputs := []int{}

// general format: RETURNVALUE NAME "(" PARAMS ")" BODY
// --------
// fnNameText
// state machine phase 0 phase 1 phase 2: break
// TODO: attributes may contain parens. also inline structs.

endRelOffset := 0
lines := utils.CountLinesCached(sym.Text)
phase := 0
for i, tok := range sym.Tokens {
switch phase {
case 0:
if tok.Type == "function" {
offset := lsp.RelativePostionWithLines(*lines, sym.Location.Range.Start, tok.Location.Range.Start)
endRelOffset = offset + strings.Index(sym.Text[offset:], ")")
phase = 1
continue
}
if c.IsEntityToken(tok) {
outputs = append(outputs, i)
}
case 1:
offset := lsp.RelativePostionWithLines(*lines, sym.Location.Range.Start, tok.Location.Range.Start)
if offset > endRelOffset {
phase = 2
continue
}
if c.IsEntityToken(tok) {
inputParams = append(inputParams, i)
}
}
}
return receiver, typeParams, inputParams, outputs
}

func (c *CxxSpec) GetUnloadedSymbol(from lsp.Token, define lsp.Location) (string, error) {
panic("TODO")
}
Loading