| This document is very much a work in progress. |
1. Intro
c-xrefactory is a software tool and a project aiming at restoring
the sources of that old, but very useful, tool to a state where it can
be enhanced and be the foundation for a highly capable refactoring
browser.
It is currently in working condition, so you can use it. For information about that, see the README.md.
1.1. Caution
As indicated by the README.md, this is a long term restoration project. So anything you find in this document might be old, incorrect, guesses, temporary holders for thoughts or theories. Or actually true and useful.
Especially names of variables, functions and modules is prone to change as understanding of them increases. They might also be refactored into something entirently different.
As this point this document is just a collection of unstructured thougths, guesses, historic anecdotes and ideas. For example, the previously existing, and also unstructured, wiki pages have just been pasted in here in an attempt to collect everything in a single document. Perhaps that will make it possible to "refactor" the information into something actually useful.
The last part of this document is an Archive where completely obsolete descriptions have been moved for future software archeologists to find.
1.2. Background
You will find some background about the project in the README.md.
This document tries to collect the knowledge and understanding about
how c-xrefactory actually works, plans for making it better, both in
terms of working with the source, its structure and its features.
Hopefully over time this will be the design documentation of
c-xrefactory, which, at that time, will be a fairly well structured
and useful piece of software.
1.3. Goal
Ultimately c-xrefactory could become the refactoring browser for
C, the one that everybody uses. As suggested by @tajmone in GitHub
issue #39, by switching to a general protocol, we could possibly plug
this in to many editors.
However, to do that we need to refactor out the protocol parts. And to do that we need a better structure, and to dare to change that, we need to understand more of the intricacies of this beast, and we need tests. So the normal legacy code catch 22 applies…
Test coverage is starting to look good, coming up to about 80% at the time of writing this. But that is mostly "application level" execution, rather than actual tests.
2. Context
c-xrefactory is designed to be an aid for programmers as they write,
edit, inspect, read and improve the code they are working on.
The editor is used for usual manual manipulation of the source
code. C-xrefactory interacts with the editor to provide navigation
and automated edits, refactorings, through the editor.
Failed to generate image: Could not load PlantUML. Either require 'asciidoctor-diagram-plantuml' or specify the location of the PlantUML JAR(s) using the 'DIAGRAM_PLANTUML_CLASSPATH' environment variable. Alternatively a PlantUML binary can be provided (plantuml-native in $PATH).
@startuml
title <size:24>System Context View: C-xrefactory</size>
set separator none
left to right direction
skinparam ranksep 60
skinparam nodesep 30
hide stereotype
<style>
root {
BackgroundColor: #ffffff;
FontColor: #444444;
}
// Element,DB
.Element-RWxlbWVudCxEQg== {
BackgroundColor: #ffffff;
LineColor: #444444;
LineStyle: 0;
LineThickness: 2;
FontColor: #444444;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Element,Person,Ext
.Element-RWxlbWVudCxQZXJzb24sRXh0 {
BackgroundColor: #686868;
LineColor: #484848;
LineStyle: 0;
LineThickness: 2;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Element,Software System
.Element-RWxlbWVudCxTb2Z0d2FyZSBTeXN0ZW0= {
BackgroundColor: #1168bd;
LineColor: #0b4884;
LineStyle: 0;
LineThickness: 2;
RoundCorner: 20;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Element,Software System,Editor,Ext
.Element-RWxlbWVudCxTb2Z0d2FyZSBTeXN0ZW0sRWRpdG9yLEV4dA== {
BackgroundColor: #686868;
LineColor: #484848;
LineStyle: 0;
LineThickness: 2;
RoundCorner: 20;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Relationship
.Relationship-UmVsYXRpb25zaGlw {
LineThickness: 2;
LineStyle: 10-10;
LineColor: #444444;
FontColor: #444444;
FontSize: 24;
}
</style>
person "==Developer\n<size:16>[Person]</size>\n\nEdits source code using an editor" <<Element-RWxlbWVudCxQZXJzb24sRXh0>> as Developer
rectangle "==Editor\n<size:16>[Software System]</size>\n\nAllows Developer to modify source code and perform refactoring operations" <<Element-RWxlbWVudCxTb2Z0d2FyZSBTeXN0ZW0sRWRpdG9yLEV4dA==>> as Editor
database "==Source Code\n<size:16>[a set of files stored on disk]</size>" <<Element-RWxlbWVudCxEQg==>> as 3
rectangle "==C-xrefactory\n<size:16>[Software System]</size>\n\nAnalyses source code, receives and processes requests for navigation and refactoring" <<Element-RWxlbWVudCxTb2Z0d2FyZSBTeXN0ZW0=>> as Cxrefactory
Editor --> Cxrefactory <<Relationship-UmVsYXRpb25zaGlw>> : "extends functionality using\n<size:16>[plugin]</size>"
Cxrefactory --> 3 <<Relationship-UmVsYXRpb25zaGlw>> : "reads source code from\n<size:16>[file I/O]</size>"
Developer --> Editor <<Relationship-UmVsYXRpb25zaGlw>> : "usual editor/IDE operations"
Developer --> Cxrefactory <<Relationship-UmVsYXRpb25zaGlw>> : "configuration and command line invocations"
Editor --> 3 <<Relationship-UmVsYXRpb25zaGlw>> : "normal editing operations"
Editor --> Cxrefactory <<Relationship-UmVsYXRpb25zaGlw>> : "navigation and refactoring requests"
Cxrefactory --> Editor <<Relationship-UmVsYXRpb25zaGlw>> : "positioning and editing responses"
Cxrefactory --> 3 <<Relationship-UmVsYXRpb25zaGlw>> : "read/analyze"
@enduml
3. Functional Overview
The c-xref program is actually a mish-mash of a multitude of features baked into one program. This is the major cause of the mess that it is source-wise.
It was
-
a generator for persistent cross-reference data
-
a reference server for editors, serving cross-reference, navigational and completion data over a protocol
-
a refactoring server (the worlds first to cross the Refactoring Rubicon)
-
an HTML cross-reference generator (probably the root of the project) (REMOVED)
-
a C macro generator for structure fill (and other) functions (REMOVED)
It is the first three that are unique and constitutes the great value of this project. The last two have been removed from the source, the last one because it was a hack and prevented modern, tidy, building, coding and refactoring. The HTML cross-reference generator has been superseeded by modern alternatives like Doxygen and is not at the core of the goal of this project.
One might surmise that it was the HTML-crossreference generator that
was the initial purpose of what the original Xrefactory was based
upon. Once that was in place the other followed, and were basically
only bolted on top without much re-architecting the C sources.
What we’d like to do is partition the project into separate parts, each having a clear usage.
The following sections are aimed at describing various features of
c-xrefactory.
3.1. Options, option files and configuration
The current version of C-xrefactory allows only two possible sets of configuration/options.
The primary storage is (currently) the file $HOME/.c-xrefrc
which stores the "standard" options for all projects. Each project has
a separate section which is started with a section marker, the project
name surrounded by square brackets, [project1].
When you start c-xref you can use the command line option -xrefrc
to request that a particular option file should be used instead of the
"standard options".
When running the edit server there seems to be no way to
indicate a different options files for different
projects/files. Although you can start the server with -xrefrc you
will be stuck with that in the whole session and for all projects.
|
3.2. LSP
The LSP protocol is a common protocol for language servers such as
clangd and c-xrefactory. It allows an editor (client) to interface
to a server to request information, such as reference positions, and
operations, such as refactorings, without knowing exactly which server
it talks to.
Recent versions of c-xrefactory have an initial implementation of a
very small portion of the LSP protocol. The plan is to fully integrate
the functionality of c-xrefactory into the LSP protocol. This will
allow use of c-xrefactory from not only Emacs but also Visual Studio
Code or any other editor that supports the LSP protocol.
4. Quality Attributes
The most important quality attributes are
-
correctness - a refactoring should never alter the behaviour of the refactored code
-
completness - no reference to a symbol should ever be missed
-
performance - a refactoring should be sufficiently quick so the user keeps focus on the task at hand
5. Constraints
TBD.
6. Principles
6.1. Reference Database and Parsing
The reference database is used only to hold externally visible identifiers to ensure that references to an identifier can be found across all files in the used source.
All symbols that are only visible inside a unit is handled by reparsing the file of interest.
6.2. TBD.
7. Software Architecture
7.1. Container View
Failed to generate image: Could not load PlantUML. Either require 'asciidoctor-diagram-plantuml' or specify the location of the PlantUML JAR(s) using the 'DIAGRAM_PLANTUML_CLASSPATH' environment variable. Alternatively a PlantUML binary can be provided (plantuml-native in $PATH).
@startuml
title <size:24>Container View: C-xrefactory</size>
set separator none
left to right direction
skinparam ranksep 60
skinparam nodesep 30
hide stereotype
<style>
root {
BackgroundColor: #ffffff;
FontColor: #444444;
}
// Element,Container
.Element-RWxlbWVudCxDb250YWluZXI= {
BackgroundColor: #438dd5;
LineColor: #2e6295;
LineStyle: 0;
LineThickness: 2;
RoundCorner: 20;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Element,Container,DB
.Element-RWxlbWVudCxDb250YWluZXIsREI= {
BackgroundColor: #438dd5;
LineColor: #2e6295;
LineStyle: 0;
LineThickness: 2;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Element,DB
.Element-RWxlbWVudCxEQg== {
BackgroundColor: #ffffff;
LineColor: #444444;
LineStyle: 0;
LineThickness: 2;
FontColor: #444444;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Element,Person,Ext
.Element-RWxlbWVudCxQZXJzb24sRXh0 {
BackgroundColor: #686868;
LineColor: #484848;
LineStyle: 0;
LineThickness: 2;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Element,Software System,Editor,Ext
.Element-RWxlbWVudCxTb2Z0d2FyZSBTeXN0ZW0sRWRpdG9yLEV4dA== {
BackgroundColor: #686868;
LineColor: #484848;
LineStyle: 0;
LineThickness: 2;
RoundCorner: 20;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Relationship
.Relationship-UmVsYXRpb25zaGlw {
LineThickness: 2;
LineStyle: 10-10;
LineColor: #444444;
FontColor: #444444;
FontSize: 24;
}
// C-xrefactory
.Boundary-Qy14cmVmYWN0b3J5 {
BackgroundColor: #ffffff;
LineColor: #0b4884;
LineStyle: 0;
LineThickness: 2;
FontColor: #1168bd;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
}
</style>
person "==Developer\n<size:16>[Person]</size>\n\nEdits source code using an editor" <<Element-RWxlbWVudCxQZXJzb24sRXh0>> as Developer
rectangle "==Editor\n<size:16>[Software System]</size>\n\nAllows Developer to modify source code and perform refactoring operations" <<Element-RWxlbWVudCxTb2Z0d2FyZSBTeXN0ZW0sRWRpdG9yLEV4dA==>> as Editor
database "==Source Code\n<size:16>[a set of files stored on disk]</size>" <<Element-RWxlbWVudCxEQg==>> as 3
rectangle "C-xrefactory\n<size:16>[Software System]</size>" <<Boundary-Qy14cmVmYWN0b3J5>> {
rectangle "==cxrefCore\n<size:16>[Container: Refactoring Browser core]</size>\n\nC Language program" <<Element-RWxlbWVudCxDb250YWluZXI=>> as Cxrefactory.cxrefCore
database "==settingsStore\n<size:16>[Container: Configuration file for project settings]</size>\n\nNon-standard format settings file" <<Element-RWxlbWVudCxDb250YWluZXIsREI=>> as Cxrefactory.settingsStore
rectangle "==editorExtension\n<size:16>[Container: Plugin]</size>\n\nExtends the Editor with c-xref operations and interfaces to the c-xrefactory API" <<Element-RWxlbWVudCxDb250YWluZXI=>> as Cxrefactory.editorExtension
database "==referencesDb\n<size:16>[Container: Persistent symbol database storing references, definitions, and metadata for all project symbols. Created via -create/-update operations, indexed by symbol hash for fast lookup]</size>\n\nCross-Reference Database (.cx files)" <<Element-RWxlbWVudCxDb250YWluZXIsREI=>> as Cxrefactory.referencesDb
}
Editor --> Cxrefactory.editorExtension <<Relationship-UmVsYXRpb25zaGlw>> : "extends functionality using\n<size:16>[plugin]</size>"
Cxrefactory.cxrefCore --> 3 <<Relationship-UmVsYXRpb25zaGlw>> : "reads source code from\n<size:16>[file I/O]</size>"
Cxrefactory.cxrefCore --> Cxrefactory.referencesDb <<Relationship-UmVsYXRpb25zaGlw>> : "builds and queries\n<size:16>[hash-based lookup]</size>"
Cxrefactory.editorExtension --> Cxrefactory.settingsStore <<Relationship-UmVsYXRpb25zaGlw>> : "writes\n<size:16>[new project wizard]</size>"
Cxrefactory.cxrefCore --> Cxrefactory.settingsStore <<Relationship-UmVsYXRpb25zaGlw>> : "read"
Cxrefactory.editorExtension --> Cxrefactory.cxrefCore <<Relationship-UmVsYXRpb25zaGlw>> : "API\n<size:16>[requests information and gets commands to modify source code]</size>"
Cxrefactory.cxrefCore --> Cxrefactory.referencesDb <<Relationship-UmVsYXRpb25zaGlw>> : "read/write"
Cxrefactory.cxrefCore --> 3 <<Relationship-UmVsYXRpb25zaGlw>> : "read/analyze"
Developer --> Editor <<Relationship-UmVsYXRpb25zaGlw>> : "usual editor/IDE operations"
Editor --> 3 <<Relationship-UmVsYXRpb25zaGlw>> : "normal editing operations"
Editor --> Cxrefactory.editorExtension <<Relationship-UmVsYXRpb25zaGlw>> : "extends\n<size:16>[Editor extension protocol]</size>"
Developer --> Cxrefactory.settingsStore <<Relationship-UmVsYXRpb25zaGlw>> : "edit"
Cxrefactory.editorExtension --> 3 <<Relationship-UmVsYXRpb25zaGlw>> : "extended c-xrefactory operations"
@enduml
7.2. Containers
At this point the description of the internal structure of the containers are tentative. The actual interfaces are not particularly clean, most code files can and do include much every other module.
| One focus area for the ongoing work is to try to pry out modules/components from the code mess by moving functions around, renaming and hiding functions, where possible. |
7.2.1. CxrefCore
Failed to generate image: Could not load PlantUML. Either require 'asciidoctor-diagram-plantuml' or specify the location of the PlantUML JAR(s) using the 'DIAGRAM_PLANTUML_CLASSPATH' environment variable. Alternatively a PlantUML binary can be provided (plantuml-native in $PATH).
@startuml
title <size:24>Component View: C-xrefactory - cxrefCore</size>
set separator none
left to right direction
skinparam ranksep 60
skinparam nodesep 30
hide stereotype
<style>
root {
BackgroundColor: #ffffff;
FontColor: #444444;
}
// Element,Component
.Element-RWxlbWVudCxDb21wb25lbnQ= {
BackgroundColor: #85bbf0;
LineColor: #5d82a8;
LineStyle: 0;
LineThickness: 2;
RoundCorner: 20;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Element,Container,DB
.Element-RWxlbWVudCxDb250YWluZXIsREI= {
BackgroundColor: #438dd5;
LineColor: #2e6295;
LineStyle: 0;
LineThickness: 2;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Element,DB
.Element-RWxlbWVudCxEQg== {
BackgroundColor: #ffffff;
LineColor: #444444;
LineStyle: 0;
LineThickness: 2;
FontColor: #444444;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Relationship
.Relationship-UmVsYXRpb25zaGlw {
LineThickness: 2;
LineStyle: 10-10;
LineColor: #444444;
FontColor: #444444;
FontSize: 24;
}
// C-xrefactory
.Boundary-Qy14cmVmYWN0b3J5 {
BackgroundColor: #ffffff;
LineColor: #0b4884;
LineStyle: 0;
LineThickness: 2;
FontColor: #1168bd;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
}
// cxrefCore
.Boundary-Y3hyZWZDb3Jl {
BackgroundColor: #ffffff;
LineColor: #2e6295;
LineStyle: 0;
LineThickness: 2;
FontColor: #438dd5;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
}
</style>
database "==Source Code\n<size:16>[a set of files stored on disk]</size>" <<Element-RWxlbWVudCxEQg==>> as 3
rectangle "C-xrefactory\n<size:16>[Software System]</size>" <<Boundary-Qy14cmVmYWN0b3J5>> {
rectangle "cxrefCore\n<size:16>[Container: Refactoring Browser core]</size>" <<Boundary-Y3hyZWZDb3Jl>> {
rectangle "==main\n<size:16>[Component: C]</size>\n\nMain program" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.main
rectangle "==xref\n<size:16>[Component: C]</size>\n\nCross-referencer" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.xref
rectangle "==server\n<size:16>[Component: C]</size>\n\nEditor Server" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.server
rectangle "==refactory\n<size:16>[Component: C]</size>\n\nRefactory" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.refactory
rectangle "==lsp\n<size:16>[Component: Language Server Protocol implementation for IDE integration - currently limited by symbol database architecture]</size>\n\nLSP Server" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.lsp
rectangle "==lspAdapter\n<size:16>[Component: Converts LSP requests to c-xrefactory operations - needs symbol database abstraction]</size>\n\nLSP Adapter" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.lspAdapter
rectangle "==cxref\n<size:16>[Component: C]</size>\n\nReference handler" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.cxref
rectangle "==cxfile\n<size:16>[Component: Manages persistent cross-reference database with symbol indexing and file-based storage]</size>\n\nReference Storage (.cx files)" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.cxfile
rectangle "==browserStack\n<size:16>[Component: Runtime symbol context stack for navigation, containing current references and symbol menus]</size>\n\nBrowser Stack" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.browserStack
rectangle "==symbolResolver\n<size:16>[Component: Converts cursor positions to symbols, loads references, and finds definitions]</size>\n\nSymbol Resolution Pipeline" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.symbolResolver
rectangle "==referenceTable\n<size:16>[Component: Runtime symbol cache loaded from .cx files for active session]</size>\n\nIn-Memory Reference Table" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.referenceTable
rectangle "==yylex\n<size:16>[Component: C]</size>\n\nLexical Analyser" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.yylex
rectangle "==parser\n<size:16>[Component: C]</size>\n\nParser" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.cxrefCore.parser
}
database "==referencesDb\n<size:16>[Container: Persistent symbol database storing references, definitions, and metadata for all project symbols. Created via -create/-update operations, indexed by symbol hash for fast lookup]</size>\n\nCross-Reference Database (.cx files)" <<Element-RWxlbWVudCxDb250YWluZXIsREI=>> as Cxrefactory.referencesDb
}
Cxrefactory.cxrefCore.main --> Cxrefactory.cxrefCore.xref <<Relationship-UmVsYXRpb25zaGlw>> : "dispatches to\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.main --> Cxrefactory.cxrefCore.server <<Relationship-UmVsYXRpb25zaGlw>> : "dispatches to\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.main --> Cxrefactory.cxrefCore.refactory <<Relationship-UmVsYXRpb25zaGlw>> : "dispatches to\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.main --> Cxrefactory.cxrefCore.lsp <<Relationship-UmVsYXRpb25zaGlw>> : "dispatches to\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.refactory --> Cxrefactory.cxrefCore.server <<Relationship-UmVsYXRpb25zaGlw>> : "uses\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.cxref --> Cxrefactory.cxrefCore.symbolResolver <<Relationship-UmVsYXRpb25zaGlw>> : "delegates symbol lookup to\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.symbolResolver --> Cxrefactory.cxrefCore.cxfile <<Relationship-UmVsYXRpb25zaGlw>> : "loads symbol data via\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.symbolResolver --> Cxrefactory.cxrefCore.referenceTable <<Relationship-UmVsYXRpb25zaGlw>> : "populates and queries\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.symbolResolver --> Cxrefactory.cxrefCore.browserStack <<Relationship-UmVsYXRpb25zaGlw>> : "builds navigation context in\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.cxfile --> Cxrefactory.cxrefCore.referenceTable <<Relationship-UmVsYXRpb25zaGlw>> : "loads symbols into\n<size:16>[batch loading]</size>"
Cxrefactory.cxrefCore.lsp --> Cxrefactory.cxrefCore.lspAdapter <<Relationship-UmVsYXRpb25zaGlw>> : "delegates to\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.lspAdapter --> Cxrefactory.cxrefCore.refactory <<Relationship-UmVsYXRpb25zaGlw>> : "uses for refactoring\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.lspAdapter --> Cxrefactory.cxrefCore.cxref <<Relationship-UmVsYXRpb25zaGlw>> : "uses for navigation\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.lspAdapter --> Cxrefactory.cxrefCore.symbolResolver <<Relationship-UmVsYXRpb25zaGlw>> : "attempts symbol lookup via\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.xref --> Cxrefactory.cxrefCore.cxref <<Relationship-UmVsYXRpb25zaGlw>> : "handles references using\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.server --> Cxrefactory.cxrefCore.cxref <<Relationship-UmVsYXRpb25zaGlw>> : "handles references using\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.refactory --> Cxrefactory.cxrefCore.cxref <<Relationship-UmVsYXRpb25zaGlw>> : "handles references using\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.parser --> Cxrefactory.cxrefCore.yylex <<Relationship-UmVsYXRpb25zaGlw>> : "reads tokenized source using\n<size:16>[buffering]</size>"
Cxrefactory.cxrefCore.xref --> Cxrefactory.cxrefCore.parser <<Relationship-UmVsYXRpb25zaGlw>> : "parses source code using\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.server --> Cxrefactory.cxrefCore.parser <<Relationship-UmVsYXRpb25zaGlw>> : "parses source code using\n<size:16>[call]</size>"
Cxrefactory.cxrefCore.yylex --> 3 <<Relationship-UmVsYXRpb25zaGlw>> : "reads source code from\n<size:16>[file I/O]</size>"
Cxrefactory.cxrefCore.cxfile --> Cxrefactory.referencesDb <<Relationship-UmVsYXRpb25zaGlw>> : "builds and queries\n<size:16>[hash-based lookup]</size>"
@enduml
cxrefCore is the core container. It does all the work when it comes
to finding and reporting references to symbols, communicating
refactoring requests as well as storing reference information for
longer term storage and caching.
Although c-xref can be used as a command line tool, which can be
handy when debugging or exploring, it is normally used in "server"
mode. In server mode the communication between the editor extension
and the cxrefCore container is a back-and-forth communication using a
non-standard protocol over standard pipes.
The responsibilities of cxrefCore can largely be divided into
-
parsing source files to create, maintain the references database which stores all inter-module references
-
parsing source files to get important information such as positions for a functions begin and end
-
managing editor buffer state (as it might differ from the file on disc)
-
performing symbol navigation
-
creating and serving completion suggestions
-
performing refactorings such as renames, extracts and parameter manipulation
At this point it seems like refactorings are performed as separate
invocations of c-xref rather than through the server interface.
7.2.2. EditorExtension
Failed to generate image: Could not load PlantUML. Either require 'asciidoctor-diagram-plantuml' or specify the location of the PlantUML JAR(s) using the 'DIAGRAM_PLANTUML_CLASSPATH' environment variable. Alternatively a PlantUML binary can be provided (plantuml-native in $PATH).
@startuml
title <size:24>Component View: C-xrefactory - editorExtension</size>
set separator none
left to right direction
skinparam ranksep 60
skinparam nodesep 30
hide stereotype
<style>
root {
BackgroundColor: #ffffff;
FontColor: #444444;
}
// Element,Component
.Element-RWxlbWVudCxDb21wb25lbnQ= {
BackgroundColor: #85bbf0;
LineColor: #5d82a8;
LineStyle: 0;
LineThickness: 2;
RoundCorner: 20;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Element,Software System,Editor,Ext
.Element-RWxlbWVudCxTb2Z0d2FyZSBTeXN0ZW0sRWRpdG9yLEV4dA== {
BackgroundColor: #686868;
LineColor: #484848;
LineStyle: 0;
LineThickness: 2;
RoundCorner: 20;
FontColor: #ffffff;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
MaximumWidth: 450;
}
// Relationship
.Relationship-UmVsYXRpb25zaGlw {
LineThickness: 2;
LineStyle: 10-10;
LineColor: #444444;
FontColor: #444444;
FontSize: 24;
}
// C-xrefactory
.Boundary-Qy14cmVmYWN0b3J5 {
BackgroundColor: #ffffff;
LineColor: #0b4884;
LineStyle: 0;
LineThickness: 2;
FontColor: #1168bd;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
}
// editorExtension
.Boundary-ZWRpdG9yRXh0ZW5zaW9u {
BackgroundColor: #ffffff;
LineColor: #2e6295;
LineStyle: 0;
LineThickness: 2;
FontColor: #438dd5;
FontSize: 24;
HorizontalAlignment: center;
Shadowing: 0;
}
</style>
rectangle "==Editor\n<size:16>[Software System]</size>\n\nAllows Developer to modify source code and perform refactoring operations" <<Element-RWxlbWVudCxTb2Z0d2FyZSBTeXN0ZW0sRWRpdG9yLEV4dA==>> as Editor
rectangle "C-xrefactory\n<size:16>[Software System]</size>" <<Boundary-Qy14cmVmYWN0b3J5>> {
rectangle "editorExtension\n<size:16>[Container: Plugin]</size>" <<Boundary-ZWRpdG9yRXh0ZW5zaW9u>> {
rectangle "==cxref.el\n<size:16>[Component: elisp]</size>" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.editorExtension.cxrefel
rectangle "==cxrefactory.el\n<size:16>[Component: elisp]</size>" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.editorExtension.cxrefactoryel
rectangle "==cxrefprotocol.el\n<size:16>[Component: elisp]</size>" <<Element-RWxlbWVudCxDb21wb25lbnQ=>> as Cxrefactory.editorExtension.cxrefprotocolel
}
}
Editor --> Cxrefactory.editorExtension.cxrefactoryel <<Relationship-UmVsYXRpb25zaGlw>> : "extends functionality using\n<size:16>[plugin]</size>"
@enduml
The EditorExtension container is responsible for plugging into an
editor of choice and handle the user interface, buffer management and
executing the refactoring edit operations.
Currently there is only one such extension supported, for Emacs,
although there existed code, still available in the repo history, for
an extension for jEdit which hasn’t been updated, modified or checked
for a long time and no longer is a part of this project.
7.2.3. ReferencesDB
The References database stores crossreferencing information for symbols visible outside the module it is defined in. Information about local/static symbols are not stored but gathered by parsing that particular source file on demand.
Currently this information is stored in a somewhat cryptic, optimized text format.
This storage can be divided into multiple files, probably for faster access. Symbols are then hashed to know which of the "database" files it is stored in. As all crossreferencing information for a symbol is stored in the same "record", this allows reading only a single file when a symbol is looked up.
8. Code
8.1. Commands
The editorExtension calls the server using command line
options. These are then converted to first a command enum starting in
OLO ("on-line operation") or AVR ("available refactoring").
Some times the server needs to call the crossreferencer which is
performed in the same manner, command line options, but this call is
internal so the wanted arguments are stored in a vector which is
passed to the xref() in the same manner as main() passes the
actual argc/argv.
Many of the commands require extra arguments like positions/markers
which are passed in as extra arguments. E.g. a rename requires the
name to rename to which is sent in the renameto= option, which is
argparsed and stored in the option structure.
Some of these extra arguments are fairly random, like -olcxparnum=
and -olcxparnum2=. This should be cleaned up.
A move towards "events" with arguments would be helpful. This would mean that we need to:
-
List all "events" that
c-xrefneed to handle -
Define the parameters/extra info that each of them need
-
Clean up the command line options to follow this
-
Create event structures to match each event and pass this to
server,xrefandrefactory -
Rebuild the main command loop to parse command line options into event structures
8.2. Passes
There is a variable in main() called firstPassing which is set and passed
down through mainEditServer() until it is reset in
mainFileProcessingInitialisations().
This is probably related to the fact that c-xref allows for passing
over the analyzed source multiple passes in case you compile the
project sources with different C defines. Variables in the c-xref
sources indicate this, e.g the loops in mainEditServerProcessFile()
and mainXrefProcessInputFile() (which are both strangely limited by
setting the maxPass variable to 1 before entering the loop…).
8.3. Parsers
C-xref uses a patched version of Berkley yacc to generate parsers. There are a number of parsers
-
C
-
Yacc
-
C expressions
There might also exist small traces of the Java parser, which was
previously a part of the free c-xref, and the C++ parser that
existed but was proprietary.
The patch to byacc is mainly to the skeleton and seems to relate mostly to handling of errors and adding a recursive parsing feature that is required for Java, which was supported previously. It is not impossible that this patch might not be necessary now that Java parsing is not necessary, but this has not been tried.
Some changes are also made to be able to accomodate multiple parsers in the same executable, mostly solved by CPP macros renaming the parsing datastructures so that they can be accessed using the standard names in the parsing skeleton. The Makefile generates the parsers and renames the generated files as appropriate.
8.4. Integrated Preprocessor
C-xrefactory includes its own integrated C preprocessor implementation rather than using the system’s preprocessor (cpp, clang preprocessor, etc.). This is a crucial architectural decision that enables core functionality.
8.4.1. Why Not Use the System Preprocessor?
Using an external preprocessor would mean that all macros would be expanded before c-xrefactory sees the code. This would make it impossible to:
-
Navigate to macro definitions
-
Show macro usage and references
-
Refactor macro names and parameters
-
Complete macro identifiers
-
See macro arguments as distinct symbols
-
Understand the code structure as the programmer wrote it
By parsing the source at the macro level, c-xrefactory operates as a source-level tool rather than a post-preprocessed tool. This allows it to work with the code as developers see and write it, preserving all macro information for navigation and refactoring.
8.4.2. Implementation Details
The integrated preprocessor is implemented in yylex.c and includes:
-
Macro definition handling (
processDefineDirective()) -
Macro expansion with argument substitution
-
Conditional compilation (
#if,#ifdef,#ifndef,#elif,#else,#endif) -
Include file processing (
#include,#include_next) -
Pragma directives (limited support)
-
Expression evaluation for
#ifdirectives (cppexp_parser.y)
8.4.3. Limitations
The integrated preprocessor does not support all modern preprocessor features:
-
Platform-specific predefined macros (like
arm64,x86_64) are not automatically defined -
Some compiler-specific extensions may not be recognized (e.g.
has_feature(),building_module())
These limitations mean that c-xrefactory may report syntax errors when encountering modern platform headers that use these features, even though the code compiles correctly with standard compilers.
8.4.4. Trade-offs
This design choice represents a fundamental trade-off:
-
Gained: Full macro-level navigation and refactoring capabilities
-
Lost: Perfect compatibility with all preprocessor extensions and platform-specific features
The benefit of macro-level refactoring is considered more valuable than perfect preprocessor compatibility, as it is a key differentiator for c-xrefactory.
8.5. Refactoring and the parsers
Some refactorings need more detailed information about the code, maybe all do?
One example, at least, is parameter manipulation. Then the refactorer
calls the appropriate parser (serverEditParseBuffer()) which
collects information in the corresponding semantic actions. This
information is stored in various global variables, like
parameterBeginPosition.
The parser is filling out a ParsedInfo structure which conveys information that can be used e.g. when extracting functions etc.
| At this point I don’t understand exactly how this interaction is performed, there seems to be no way to parse only appropriate parts, so the whole file need to be re-parsed. |
Findings:
-
some global variables are set as a result of command line and arguments parsing, depending on which "command" the server is acting on
-
the semantic rules in the parser(s) contains code that matches these global variables and then inserts special lexems in the lexem stream
One example is how a Java 'move static method' was performed. It
requires a target position. That position is transferred from command
line options to global variables. When the Java parser was parsing a
class or similar it (or rather the lexer) looks at that "ddtarget
position information" and inserts a OL_MARKER_TOKEN in the stream.
| TODO: What extra "operation" the parsing should perform and return data for should be packaged into some type of "command" or parameter object that should be passed to the parser, rather than relying on global variables. |
8.6. Reading Files
Here are some speculations about how the complex file reading is structured.
Each file is identified by a filenumber, which is an index into the
file table, and seems to have a lexBuffer tied to it so that you can
just continue from where ever you were. That in turn contains a
CharacterBuffer that handles the actual character reading.
And there is also an "editorBuffer"…
The intricate interactions between these are hard to follow as the code here are littered with short character names which are copies of fields in the structures, and infested with many macros, probably in an ignorant attempt at optimizing. ("The root of all evil is premature optimization" and "Make it work, make it right, make it fast".)
It seems that everything start in initInput() in yylex.c where the
only existing call to fillFileDescriptor() is made. But you might
wonder why this function does some initial reading, this should be
pushed down to the buffers in the file descriptor.
8.6.1. Lexing/scanning
Lexing/scanning is performed in two layers, one in lexer.c which
seems to be doing the actual lexing into lexems which are put in a
lexembuffer. This contains a sequence of encoded and compressed
symbols which first has a LexemCode which is followed by extra data,
like Position. These seems to always be added but not always necessary.
The higher level "scanning" is performed, as per ususal,
by yylex.c. lexembuffer defines some functions to put and get
lexems, chars (identifiers and file names?) as well as integers and
positions.
At this point the put/get lexem functions take a pointer to a pointer to chars (which presumably is the lexem stream in the lexembuffer) which it also advances. This requires the caller to manage the LexemBuffer’s internal pointers outside and finally set them right when done.
It would be much better to call the "putLexem()"-functions with a
lexemBuffer but there seems to be a few cases where the destination
(often dd) is not a lexem stream inside a lexemBuffer. These might
be related to macro handling.
| This is a work-in-progress. Currently most of the "normal" usages are prepared to use the LexemBuffer’s pointers. But the handling of macros and defines are cases where the lexems are not put in a LexemBuffer. See the TODO.org for current status of this Mikado sequence. |
8.6.2. Semantic information
As the refactoring functions need some amount of semantic information,
in the sense of information gathered during parsing, this information
is collected in various ways when c-xref calls the "sub-task" to do
the parsing required.
Two structures hold information about various things, among which are
the memory index at certain points of the parsing. Thus it is possible
to verify e.g. that a editor region does not cover a break in block or
function structure. This structure is, at the point of writing, called
parsedInfo and definitely need to be tidied up.
8.7. Reference Database
c-xref run in "xref" mode creates, or updates, a database of
references for all externally visible symbols it encounters.
A good design should have a clean and generic interface to the reference database, but this is still a work in progress to chisel this out.
8.7.1. Architecture Overview
c-xrefactory’s core functionality relies on a sophisticated symbol database that stores cross-references, definitions, and usage information for all symbols in a project. The database is implemented as a collection of binary .cx files and supports:
-
Creation via
-createoperations that parse all project files -
Updates via
-updateoperations (incremental or full) -
Queries during symbol lookup operations
8.7.2. Database Structure and Format
The symbol database uses a hash-partitioned file structure:
cxrefs/
├── files # File metadata and paths
├── 0000 # Symbol data for hash bucket 0
├── 0001 # Symbol data for hash bucket 1
└── ... # Additional hash buckets based on referenceFileCount
Each .cx file contains structured records with specific keys:
-
CXFI_FILE_NAME: File paths and metadata -
CXFI_SYMBOL_NAME: Symbol names, types, and attributes -
CXFI_REFERENCE: Individual symbol references with positions and usage types
8.7.3. Symbol Resolution Pipeline
The symbol lookup process follows this pipeline:
1. Cursor Position Input
↓
2. Parse current file to identify symbol at position
↓
3. scanReferencesToCreateMenu(symbolName)
↓
4. Load symbol data from .cx files
↓
5. Populate sessionData.browserStack
↓
6. Find best definition via olcxOrderRefsAndGotoDefinition()
↓
7. Navigate to definition position
8.7.4. Key Data Structures
Browser Stack (sessionData.browserStack)
The browser stack is the runtime data structure for symbol navigation:
typedef struct {
OlcxReferences *top; // Current symbol being browsed
OlcxReferences *root; // Stack base
} OlcxReferencesStack;
typedef struct {
Reference *current; // Current reference
Reference *references; // All references for symbol
SymbolsMenu *symbolsMenu; // Available symbols for selection
Position callerPosition; // Where lookup was initiated
ServerOperation operation; // Type of operation (OLO_PUSH, etc.)
} OlcxReferences;
Reference Information
typedef struct {
Position position; // File, line, column
Usage usage; // UsageDefined, UsageDeclared, UsageUsed
struct Reference *next; // Linked list of references
} Reference;
typedef struct {
char *linkName; // Symbol name with scope information
Type type; // Symbol type (function, variable, etc.)
Storage storage; // Storage class
Scope scope; // Visibility scope
int includedFileNumber; // File containing symbol
Reference *references; // All references to this symbol
} ReferenceItem;
8.7.5. Database Operations
Database Creation (-create)
-
Parse all project files using C/Yacc parsers
-
Generate
ReferenceItementries for each symbol -
Create
Referenceentries for each symbol usage -
Write structured records to
.cxfiles -
Build hash-based index for fast lookup
Database Updates (-update)
-
Full Update: Rebuild entire database
-
Fast Update: Only process modified files based on timestamps
-
Incremental: Smart detection of changed dependencies
Symbol Lookup (OLO_PUSH operations)
-
scanReferencesToCreateMenu(symbolName)loads symbol data -
createSelectionMenu()builds navigation menus -
olProcessSelectedReferences()populates browser stack -
olcxOrderRefsAndGotoDefinition()finds best definition
8.7.6. LSP Integration Challenges
Architectural Mismatch
The current architecture was designed for batch processing and persistent databases, while LSP requires on-demand processing and responsive queries.
Current LSP Problems:
-
Persistent File Dependency: LSP
findDefinition()callsscanReferencesToCreateMenu()which expects pre-existing.cxfiles -
Project-Wide Requirement: Full project analysis required before individual file operations
-
Batch Processing Model: No support for incremental, per-request symbol resolution
-
Cold Start Problem: New projects have no
.cxfiles, causing all LSP operations to fail
Error Flow in LSP Mode:
LSP textDocument/definition request
↓
findDefinition() called
↓
scanReferencesToCreateMenu() called
↓
No .cx files exist → empty results
↓
browserStack remains empty
↓
All definition requests return same default position
Performance Characteristics
| Operation | File-Based (.cx) | On-Demand Parsing |
|---|---|---|
Cold Start |
Requires |
Parse file immediately |
Warm Queries |
O(1) hash lookup |
O(file_size) parsing |
Memory Usage |
Low (streaming) |
High (in-memory cache) |
Incremental Updates |
Smart file tracking |
Per-file invalidation |
Multi-project |
Separate databases |
Workspace-scoped |
| A proposal for a unified symbol database architecture has been documented. See Proposed Unified Symbol Database in the Proposed Refactorings chapter. |
8.7.7. CXFILE
The current implementation of the reference database is file based, with an optimized storage format.
There is limited support to automatically keep these updated during an edit-compile cycle, you might have to update manually now and then.
The project settings (or command line options) indicate where the
file(s) are created and one option controls the number of files to be
used, -refnum.
This file (or files) contains compact, but textual representations of the cross-reference information. Format is somewhat complex, but here are somethings that I think I have found out:
-
the encoding has single character markers which are listed at the top of cxfile.c
-
the coding seems to often start with a number and then a character, such as '4l' (4 ell) means line 4, 23c mean column 23
-
references seems to be optimized to not repeat information if it would be a repetition, such as '15l3cr7cr' means that there are two references on line 15, one in column 3 the other in column 7
-
so there is a notion of "current" for all values which need not be repeated
-
e.g. references all use 'fsulc' fields, i.e. file, symbol index, usage, line and column, but do not repeat a 'fsulc' as long as it is the same
-
some "fields" have a length indicator before, such as filenames ('6:/abc.c') indicated by ':' and version information ('34v file format: C-xrefactory 1.6.0 ') indicated by 'v'.
So a line might say
12205f 1522108169p m1ia 84:/home/...
The line identifies the file with id 12205. The file was last included in an update of refs at sometime which is identified by 1522108169 (mtime), has not been part of a full update of xrefs, was mentioned on the command line. (I don’t know what the 'a' means…) Finally, the file name itself is 84 characters long.
| TODO: Build a tool to decipher this so that tests can query the generated data for expected data. This is now partly ongoing in the 'utils' directory. |
8.7.8. Reference Database Reading
All information about an externally visible symbol is stored in one, and only one reference file, determined by hashing the linkname of the symbol. So it will always suffice to read one reference file when consulting the reference database (in the form of CXFILE) for a symbol.
The reading of the CXFILE format is controlled by `scanFunctionTable`s. These consists of a list of entries, one for each key/tag/recordCode (see format description above) that the scan will process.
As the reference file reading encounters a key/tag/recordCode it will consult the table and see if there is an entry pointing to a handler function for that key/tag/recordCode. If so, it will be called.
8.8. Editor Plugin
The editor plugin has three different responsibilities:
-
serve as the UI for the user when interacting with certain
c-xrefrelated functions -
query
c-xref serverfor symbol references and support navigating these in the source -
initiate source code operations ("refactorings") and execute the resulting edits
Basically Emacs (and probably other editors) starts c-xref in
"server-mode" using -server which connects the editor
with c-xref through stdout/stdin. If you have (setq
c-xref-debug-mode t) this command is logged in the *Messages* buffer
with the prefix "calling:".
Commands are sent from the editor to the server on its standard input.
They looks very much like normal command line options, and in fact
c-xref will parse that input in the same way using the same
code. When the editor sends an end-of-options line, the server will
start executing whatever was sent, and return some information in the
file given as an -o option when the editor starts the c-xref
server process. The file is named and created by the editor and
usually resides in /tmp. With c-xref-debug-mode set to on this is
logged as "sending:". If you (setq c-xref-debug-preserve-tmp-files
t) Emacs will also not delete the temporary files it creates so that
you can inspect them afterwards.
When the server has finished processing the command and placed the
output in the output file it sends a <sync> reply.
The editor can then pick up the result from the output file and do what it needs to do with it ("dispatching:").
8.8.1. Invocations
The editor invokes a new c-xref process for the following cases:
-
Refactoring
Each refactoring operation calls a new instance of
c-xref? -
Create Project
When a
c-xreffunction is executed in the editor and there is no project covering that file, an interactive "create project" session is started, which is run by a separatec-xrefprocess.
8.8.2. Buffers
There is some magical editor buffer management happening inside of
c-xref which is not clear to me at this point. Basically it looks
like the editor-side tries to keep the server in sync with which
buffers are opened with what file…
At this point I suspect that -preload <file1> <file2> means that the
editor has saved a copy of <file1> in <file2> and requests the server
to set up a "buffer" describing that file and use it instead of the
<file1> that recides on disk.
This is essential when doing refactoring since the version of the file
most likely only exists in the editor, so the editor has to tell the
server the current content somehow, this is the -preload option.
8.9. Editor Server
When serving an editor the c-xrefactory application is divided into
the server, c-xref and the editor part, at this point only Emacs:en
are supported so that’s implemented in the
editor/Emacs-packages.
8.9.1. Interaction
The initial invocation of the edit server creates a process with which communication is over stdin/stdout using a protocol which from the editor is basically a version of the command line options.
When the editor has delivered all information to the server it sends
'end-of-option' as a command and the edit server processes whatever it
has and responds with <sync> which means that the editor can fetch
the result in the file it named as the output file using the '-o'
option.
| As long as the communication between the editor and the server is open, the same output file will be used. This makes it hard to catch some interactions, since an editor operation might result in multiple interactions, and the output file is then re-used. |
Setting the emacs variable c-xref-debug-mode forces the editor to
copy the content of such an output file to a separate temporary file
before re-using it.
For some interactions the editor starts a completely new and fresh
c-xref process, see below. And actually you can’t do refactorings
using the server, they have to be separate calls. (Yes?) I have yet to
discover why this design choice was made.
There are many things in the sources that handles refactorings
separately, such as refactoring_options, which is a separate copy of
the options structure used only when refactoring.
|
8.9.2. Protocol
Communication between the editor and the server is performed using
text through standard input/output to/from c-xref. The protocol is
defined in src/protocol.tc and must match editor/emacs/c-xrefprotocol.el.
The definition of the protocol only caters for the server→editor part, the editor→server part consists of command lines resembling the command line options and arguments, and actually is handled by the same code.
The file protocol.tc is included in protocol.h and protocol.c
which generates definitions and declarations for the elements through
using some macros.
There is a similar structure with c-xrefprotocol.elt which
includes protocol.tc to wrap the PROTOCOL_ITEMs into
defvars.
There is also some Makefile trickery that ensures that the C and elisp impementations are in sync.
One noteable detail of the protocol is that it carries strings in their native format, utf-8. This means that lengths need to indicate characters not bytes.
8.9.3. Invocation of server
The editor fires up a server and keeps talking over the established channel (elisp function 'c-xref-start-server-process'). This probably puts extra demands on the memory management in the server, since it might need to handle multiple information sets and options (as read from a .cxrefrc-file) for multiple projects simultaneously over a longer period of time. (E.g. if the user enters the editor starting with one project and then continues to work on another then new project options need to be read, and new reference information be generated, read and cached.)
| TODO: Figure out and describe how this works by looking at the elisp-sources. |
FINDINGS:
-
c-xref-start-server-process in c-xref.el
-
c-xref-send-data-to-running-process in c-xref.el
-
c-xref-server-call-refactoring-task in c-xref.el
8.9.4. Communication Protocol
The editor server is started using the appropriate command line option and then it keeps the communication over stdin/stdout open.
The editor part sends command line options to the server, which looks something like (from the read_xrefs test case):
-encoding=european -olcxpush -urldirect "-preload" "<file>" "-olmark=0" "-olcursor=6" "<file>" -xrefrc ".c-xrefrc" -p "<project>" end-of-options
In this case the "-olcxpush" is the operative command which results in the following output
<goto> <position-lc line=1 col=4 len=66>CURDIR/single_int1.c</position-lc> </goto>
As we can see from this interaction, the server will handle (all?) input as a command line and manage the options as if it was a command line invocation.
This explains the intricate interactions between the main program and the option handling.
The reason behind this might be that a user of the editor might be editing files on multiple projects at once, so every interrogation/operation needs to clearly set the context of that operation, which is what a user would do with the command line options.
8.9.5. OLCX Naming
It seems that all on-line editing server functions have an olcx
prefix, "On-Line C-Xrefactory", maybe…
8.10. Refactoring
This is of course, the core in why I want to restore this, to get at its refactoring capabilities. So far, much is not understood, but here are some bits and pieces.
8.10.1. Editor interface
One thing that really confused me in the beginning was that the editor, primarily Emacs, don’t use the actual server that it has started for refactoring operations (and perhaps for other things also?). Instead it creates a separate instance with which it talks to about one refactoring.
I’ve just managed to create the first automatic test for refactorings, olcx_refactory_rename. It was created by running the sandboxed emacs to record the communication and thus finding the commands to use.
Based on this learning it seems that a refactoring typically is a single invocation of c-xref with appropriate arguments (start & stop markers, the operation, and so on) and the server then answers with a sequence of operations, like
<goto>
<position-off off=3 len=<n>>CURDIR/test_source/single_int1.c</position-off>
</goto>
<precheck len=<n>> single_int_on_line_1_col_4;</precheck>
<replacement>
<str len=<n>>single_int_on_line_1_col_4</str> <str len=<n>>single_int_on_line_1_col_44</str>
</replacement>
8.10.2. Interactions
I haven’t investigated the internal flow of such a sequence, but it is starting to look like c-xref is internally re-reading the initialization, I’m not at this point sure what this means, I hope it’s not internal recursion…
8.10.3. Extraction
Each type of refactoring has it’s own little "language". E.g. extracting a method/function using -refactory -rfct-extract-function will return something like
<extraction-dialog type=newFunction_> <str len=20> newFunction_(str);
</str>
<str len=39>static void newFunction_(char str[]) {
</str>
<str len=3>}
</str>
<int val=2 len=0></int>
</extraction-dialog>
So there is much logic in the editor for this. I suspect that the three <str> parts are
-
what to replace the current region with
-
what to place before the current region
-
what to place after the current region
If this is correct then all extractions copy the region verbatim and then the server only have to figure out how to "glue" that to a semantically correct call/argument list.
As a side note the editor asks for a new name for the function and then calls the edit server with a rename request (having preloaded the new source file(s) of course).
8.10.4. Protocol
Dechiffrering the interaction between an editor and the edit server in
c-xrefactory isn’t easy. The protocol isn’t very clear or
concise. Here I’m starting to collect the important bits of the
invocation, the required and relevant options and the returned
information.
The test cases for various refactoring operations should give you some more details.
All of these require a -p (project) option to know which c-xref
project options to read.
General Principles
Refactorings are done using a separate invocation, the edit server mode cannot handle refactorings. At least that is how the Emacs client does it (haven’t looked at the Jedit version).
I suspect that it once was a single server that did both the symbol
management and the refactoring as there are remnants of a separate
instance of the option structure named "refactoringOptions". Also the
check for the refactoring mode is done using
options.refactoringRegime == RegimeRefactory which seems strange.
Anyway, if the refactoring succeeds the suggested edits is as per usual in the communications buffer.
However, there are a couple of cases where the communcation does not end there. Possibly because the client needs to communicate some information back before the refactoring server can finish the job, like presenting some menu selection.
My guess at this point is that it is the refactoring server that closes the connection when it is done…
Rename
Invocation: -rfct-rename -renameto=NEW_NAME -olcursor=POSITION FILE
Semantics: The symbol under the cursor (at POSITION in FILE) should be renamed (replaced at all occurrences) by NEW_NAME.
Result: sequence of
<goto>
<position-off off=POSITION len=N>FILE</position-off>
</goto>
<precheck len=N>STRING</precheck>
followed by sequence of
<goto>
<position-off off=POSITION len=N>FILE</position-off>
</goto>
<replacement>
<str len=N>ORIGINAL</str> <str len=N>REPLACEMENT</str>
</replacement>
Protocol Messages
- <goto>{position-off}</goto> → editor
-
Request the editor to move cursor to the indicated position (file, position).
- <precheck len={int}>{string}</precheck> → editor
-
Requests that the editor verifies that the text under the cursor matches the string.
- <replacement>{str}{str}</replacement>
-
Requests that the editor replaces the string under the cursor, which should be 'string1', with 'string2'.
- <position-off off={int} len={int}>{absolute path to file}</position-off>
-
Indicates a position in the given file. 'off' is the character position in the file.
8.11. Memory handling
c-xrefactory uses custom memory management via arena allocators rather than malloc/free for performance-critical operations.
See the Modules chapter for the design and architecture of the Memory module, and the Data Structures chapter for details on the arena allocator data structure and allocation model.
For debugging memory issues, especially arena lifetime violations, see the Development Environment chapter.
8.11.1. The Memory Type
Memory allocation is managed through the Memory structure, which implements an arena/bump allocator. Different memory arenas serve different purposes:
-
cxMemory- Cross-reference database (with overflow handling) -
ppmMemory- Preprocessor macro expansion -
macroBodyMemory- Macro definition storage -
macroArgumentsMemory- Macro argument expansion -
fileTableMemory- File table entries
See Modules chapter for detailed description of each arena’s purpose and lifetime.
8.11.2. Option Memory
The optMemory arena requires special handling because Options structures are copied during operation. When copying, all pointers into option memory must be adjusted to point into the target structure’s memory area, not the source’s.
Functions like copyOptions() perform this pointer adjustment through careful memory arithmetic, traversing a linked list of all memory locations that need updating.
| The linked list nodes themselves are allocated in the Options structure’s dynamic memory. |
8.12. Configuration
The legacy c-xref normally, in "production", uses a common configuration file in the
users home directory, .c-xrefrc. When a new project is defined its options will be
stored in this file as a new section.
It is possible to point to a specific configuration file using the command line option
-xrefrc which is used extensively in the tests to isolate them from the users
configuration.
Each "project" or "section" requires a name of the "project", which is the argument to
the -p command line option. And it may contain most other command line options on one
line each. These are always read, unless -no-stdop is used, before anything else. This
allows for different "default" options for each project.
8.12.1. Options
There are three possible sources for options.
-
Configuration files (~/.c-xrefrc)
-
Command line options at invocation, including server
-
Piped options sent to the server in commands
Not all options are relevant in all cases.
All options sources uses exactly the same format so that the same code for decoding them can be used.
8.12.2. Logic
When the editor has a file open it needs to "belong" to a project. The logic for finding which is very intricate and complicated.
In this code there is also checks for things like if the file is already in the index, if the configuration file has changed since last time, indicating there are scenarios that are more complicated (the server, obviously).
But I also think this code should be simplified a lot.
9. Modules
The current state of c-xrefactory is not such that clean modules can
easily be identified and located. This is obviously one important goal
of the continuing refactoring work.
To be able to do that we need to understand the functionality enough so that clusters of code can be refactored to be more and more clear in terms of responsibilities and interfaces.
This section makes a stab at identifying some candidated to modules,
as illustrated by the component diagram for cxrefCore.
9.1. Yylex
9.1.1. Responsibilities
-
Transform source text to sequences of lexems and additional information
-
Register and apply C pre-processor macros and defines as well as defines made as command line options (
-D) -
Handle include files by pushing and poping read contexts
9.1.2. Interface
The yylex module has the standard interface required by any
yacc-based parser, which is a simple yylex(void) function.
9.2. Parser
9.3. Xref
9.4. Server
9.5. Refactory
9.6. Cxref
9.7. Main
9.8. Memory
9.8.1. Responsibilities
The Memory module provides arena-based allocation for performance-critical and request-scoped operations:
-
Fast allocation for macro expansion and lexical analysis
-
Bulk deallocation for request-scoped cleanup
-
Multiple specialized arenas for different data lifetimes
-
Overflow detection and optional dynamic resizing
9.8.2. Design Rationale
Historical Context
In the 1990s when c-xrefactory originated, memory was scarce. The design had to:
-
Minimize allocation overhead (no malloc/free per token)
-
Support large projects despite limited RAM
-
Allow overflow recovery via flushing and reuse
-
Enable efficient bulk cleanup
Most memory arenas use statically allocated areas. Only cxMemory supports dynamic resizing to handle out-of-memory situations by discarding, flushing and reusing memory. This forced implementation of a complex caching strategy since overflow could happen mid-file.
Modern Benefits
Even with abundant modern memory, arena allocators provide:
-
Performance: Bump pointer allocation is ~10x faster than malloc
-
Cache locality: Related data allocated contiguously
-
Automatic cleanup: Bulk deallocation prevents leaks
-
Request scoping: Natural fit for parsing/expansion operations
9.8.3. Arena Types and Lifetimes
| Arena | Purpose | Lifetime |
|---|---|---|
cxMemory |
Symbol database, reference tables, cross-reference data |
File or session |
ppmMemory |
Preprocessor macro expansion buffers (temporary allocations) |
Per macro expansion |
macroBodyMemory |
Macro definition storage |
Session |
macroArgumentsMemory |
Macro argument expansion |
Per macro invocation |
fileTableMemory |
File metadata and paths |
Session |
optMemory |
Command-line and config option strings (with special pointer adjustment) |
Session |
9.8.4. Key Design Patterns
Marker-Based Cleanup
Functions save a marker before temporary allocations:
char *marker = ppmAllocc(0); // Save current index
// ... temporary allocations ...
ppmFreeUntil(marker); // Bulk cleanup
Buffer Growth Pattern
Long-lived buffers that may need to grow:
// Allocate initial buffer
bufferDesc.buffer = ppmAllocc(initialSize);
// ... use buffer, may need growth ...
// Free temporaries FIRST
ppmFreeUntil(marker);
// NOW buffer can grow (it's at top-of-stack)
expandPreprocessorBufferIfOverflow(&bufferDesc, writePointer);
Overflow Handling
The cxMemory arena supports dynamic resizing:
bool cxMemoryOverflowHandler(int n) {
// Attempt to resize arena
// Return true if successful
}
memoryInit(&cxMemory, "cxMemory", cxMemoryOverflowHandler, initialSize);
When overflow occurs, handler can:
-
Resize the arena (if within limits)
-
Flush old data and reset
-
Signal failure (fatal error)
9.8.5. Interface
Key functions (see memory.h):
// Initialization
void memoryInit(Memory *memory, char *name,
bool (*overflowHandler)(int n), int size);
// Allocation
void *memoryAlloc(Memory *memory, size_t size);
void *memoryAllocc(Memory *memory, int count, size_t size);
// Reallocation (only for most recent allocation)
void *memoryRealloc(Memory *memory, void *pointer,
size_t oldSize, size_t newSize);
// Bulk deallocation
size_t memoryFreeUntil(Memory *memory, void *marker);
// Guards
bool memoryIsAtTop(Memory *memory, void *pointer, size_t size);
9.8.6. Common Pitfalls
See the "Arena Allocator Lifetime Violations" section in the Development Environment chapter for:
-
Attempting to resize buffers not at top-of-stack
-
Calling
FreeUntil()too late -
Mixing arena lifetimes
9.8.7. Future Directions
Modern systems have abundant virtual memory. Possible improvements:
-
Simplify overflow handling - Allocate larger initial arenas
-
Separate lifetime management - Don’t mix temporary and long-lived allocations
-
Consider alternatives - Linear allocators for some use cases
-
Add debug modes - Track allocation patterns and detect violations
The experimental FlushableMemory type explores some of these ideas but hasn’t replaced current implementation.
9.9. Cxfile
9.9.1. Responsibilities
Read and write the CXref database in "plain" text format.
9.9.2. File format
The current file format for the cross-reference data consists of records with the general format
<number><key>[<value>]
There are two important types of lines, a file information line and a symbol information line.
The actual keys are documented in cxfile.c, but here is an example
file information line:
32571f 1715027668m 21:/usr/include/ctype.h
First we have two simple value/key pairs. We see "32571f" indicating that this is file information for file with file number 32571.
Secondly we have "1715027668m". This is the modification time of the file which is stored to be able to see if that file has been updated since the reference database was last written.
And the third part is "21:/usr/include/ctype.h", which is of a record type that is a bit more complex. The number is the length of the value. The ':' indicates that the record is a filename.
9.10. c-xref.el
9.11. c-xrefactory.el
10. Data Structures
There are a lot of different data structures used in c-xrefactory.
This is a first step towards visualising some of them.
10.1. ReferenceItems and References
This is a fundamental pair. A ReferenceItem is the symbol that
occurs at the locations that References indicate.
Each ReferenceItem has a linked list of `Reference`s, each denoting
one occurence of that "symbol".
10.2. Symbols and References
There is also a structure called Symbol. But, why is there no
connection between the symbols and the references?!?
So what are these actually?
Failed to generate image: Could not load PlantUML. Either require 'asciidoctor-diagram-plantuml' or specify the location of the PlantUML JAR(s) using the 'DIAGRAM_PLANTUML_CLASSPATH' environment variable. Alternatively a PlantUML binary can be provided (plantuml-native in $PATH).
class Symbol {
char *name
Position position
SymbolBits bits
}
Symbol o-- Symbol : next
class SymbolList {
}
SymbolList o-- Symbol : symbol
SymbolList o-- SymbolList : next
class ReferencesItem {
char *name
ReferencesBits bits
}
ReferencesItem o-- Reference : references
ReferencesItem o-- ReferencesItem : next
class Reference {
Usage usage
Position position
}
Reference o-- Reference : next
10.3. Files and Buffers
Many strange things are going on with reading files so that is not completely understood yet.
Here is an initial attempt at illustrating how some of the file and text/lexem buffers are related.
Failed to generate image: Could not load PlantUML. Either require 'asciidoctor-diagram-plantuml' or specify the location of the PlantUML JAR(s) using the 'DIAGRAM_PLANTUML_CLASSPATH' environment variable. Alternatively a PlantUML binary can be provided (plantuml-native in $PATH).
class FileDescriptor {
}
FileDescriptor o-- LexemBuffer : lexemBuffer
class LexemBuffer {
Lexem[] lexemStream
}
LexemBuffer o-- CharacterBuffer : buffer
class CharacterBuffer {
char[] : chars
}
class LexemStream {
char* : macroName
InputType : inputType
}
LexemStream --> LexemBuffer : beginningOfBuffer, endOfBuffer, currentLexemP (into .lexemStream)
It would be nice if the LexemStream structure could point to a
LexemBuffer instead of holding separate pointers which are
impossible to know what they actually point to…
|
| This could be achieved if we could remove the CharacterBuffer from LexemBuffer and make that a reference instead of a composition. Then we’d need to add a CharacterBuffer to the structures that has a LexemBuffer as a component (if they use it). |
10.4. Modes
c-xrefactory operates in different modes ("regimes" in original
c-xref parlance):
-
xref - batch mode reference generation
-
server - editor server
-
refactory - refactory browser
The default mode is "xref". The command line options -server and -refactory
selects one of the other modes. Branching is done in the final lines in
main().
The code for the modes are intertwined, probably through re-use of already existing functionality when extending to a refactoring browser.
One evidence for this is that the refactory module calls the "main task" as a "sub-task". This forces some intricate fiddling with the options data structure, like copying it. Which I don’t fully understand yet.
TODO?: Strip away the various "regimes" into more separated concerns and handle options differently.
10.5. Options
The Options datastructure is used to collect options from the
command line as well as from options/configuration files and piped
options from the editor client using process-to-process
communication.
It consists of a collection of fields of the types
-
elementary types (bool, int, …)
-
string (pointers to strings)
-
lists of strings (linked lists of pointers to strings)
10.5.1. Allocation & Copying
Options has its own allocation using optAlloc which allocates in a
separate area, currently part of the options structure and utilizing
"dynamic allocation" (dm_ functions on the Memory structure).
The Options structure are copied multiple times during a session, both
as a backup (savedOptions) and into a separate options structure
used by the Refactorer (refactoringOptions).
Since the options memory is then also copied, all pointers into the options memory need to be updated. To be able to do this, the options structure contains lists of addresses that needs to by "shifted".
When an option with a string or string list value is modified the option is registered in either the list of string valued options or the list of string list valued options. When an options structure is copied it must be performed using a deep copy function which "shifts" those options and their values (areas in the options memory) in the copy so that they point into the memory area of the copy, not the original.
After the deep copy the following point into the option memory of the copy
-
the lists of string and string list valued options (option fields)
-
all string and string valued option fields that are used (allocated)
-
all list nodes for the used option (allocated)
-
all list nodes for the string lists (allocated)
10.6. Arena Allocators (Memory)
Arena allocators (also called region-based or bump allocators) are the fundamental memory management strategy used throughout c-xrefactory for performance-critical operations like macro expansion and lexical analysis.
10.6.1. The Memory Structure
typedef struct memory {
char *name; // Arena name for diagnostics
bool (*overflowHandler)(int n); // Optional resize handler
int index; // Next allocation offset (bump pointer)
int max; // High-water mark
size_t size; // Total arena size
char *area; // Actual memory region
} Memory;
10.6.2. Allocation Model
Arena allocators use bump pointer allocation:
-
Allocation: Return
&area[index], thenindex += size -
Deallocation: Bulk rollback via
FreeUntil(marker) -
Reallocation: Only possible for most recent allocation
This is extremely fast (O(1) allocation) but requires stack-like discipline for deallocation.
10.6.3. Stack-Like Discipline
Arenas follow LIFO (last-in-first-out) cleanup:
marker = ppmAllocc(0); // Save current index
temp1 = ppmAllocc(100); // Allocate
temp2 = ppmAllocc(200); // Allocate
// Use temp1, temp2...
ppmFreeUntil(marker); // Free both temp1 and temp2
10.6.4. Key Constraint: Top-of-Stack Reallocation
Only the most recent allocation can be resized:
buffer = ppmAllocc(1000); // Allocate buffer
temp = ppmAllocc(500); // Allocate temporary
ppmReallocc(buffer, ...); // ❌ FAILS - buffer not at top
This constraint is enforced by guards in memory.c (see Development Environment chapter).
10.6.5. Memory Arena Types
c-xrefactory uses specialized arenas for different purposes (see Modules chapter for details):
-
cxMemory- Cross-reference database and symbol tables -
ppmMemory- Preprocessor macro expansion (temporary) -
macroBodyMemory- Macro body buffers -
macroArgumentsMemory- Macro argument expansion -
fileTableMemory- File table entries -
optMemory- Option strings (with special pointer adjustment)
11. Algorithms
The code does not always explain the algorithms that it implements. This chapter will ultimately be a description of various algorithms used by c-xrefactory.
11.1. How is an Extract refactoring performed?
The region (mark and point/cursor positions) is sent to the c-xref
server in a -refactory -rfct-extract command.
The server parses the relevant file and sets some information that can be used in some prechecks that are then performed, such as structure check, and then the server answers with
<extraction-dialog>
<str .... /str>
<str .... /str>
<str .... /str>
</extraction-dialog>
The first string is the code that will replace the extracted code, such as a call to the extracted function. The second string is the header part that will preceed the extracted code ("preamble"), and the third is then of course any code that needs to go after the extracted code ("postamble").
The actual code in the region is never sent to, or returned from, the server. This is handled completely by the editor extension, and used verbatim (except if it is a macro that is extracted, in which case each line is terminated by the backslash) so no changes to that code can be made.
The pre- and post-ambles might be of varying complexity. E.g. when extracting a macro, the postamble can be completely empty. When extracting a function both may contain code to transfer and restore parameters into local variables to propagate in/out variables as required.
-
The editor then requests a name from the user that it will use in a rename operation that renames the default named function/macro/variable.
11.2. How does lexem stream management work?
Lexical analysis uses a stack of LexemStream structures to handle nested macro expansions. The key insight is that the stream type acts as a discriminator for buffer ownership and cleanup strategy.
11.2.1. The Stream Types
typedef enum {
NORMAL_STREAM, // File or local buffer
MACRO_STREAM, // Macro expansion
MACRO_ARGUMENT_STREAM, // Macro argument expansion
} LexemStreamType;
Historically, there was also a CACHED_STREAM type when the caching mechanism was still active. This confirms that stream types are fundamentally about buffer ownership and refill strategy - each type encodes where the buffer came from and how to handle it when exhausted.
|
- NORMAL_STREAM
-
Buffer from file’s
lexemBufferor a local temporary. Not allocated from arena memory, so no cleanup needed when stream exhausted. - MACRO_STREAM
-
Buffer allocated from
macroBodyMemoryarena during macro expansion. Must callmbmFreeUntil(stream.begin)when popping from stack to free the arena allocation. - MACRO_ARGUMENT_STREAM
-
Buffer allocated from
ppmMemoryarena during macro argument expansion. SignalsEND_OF_MACRO_ARGUMENT_EXCEPTIONwhen exhausted (cleanup handled by caller).
11.2.2. The Refill Algorithm
When currentInput runs out of lexems (read >= write), refillInputIfEmpty() uses the stream type to decide what to do:
while (currentInput.read >= currentInput.write) {
LexemStreamType inputType = currentInput.streamType;
if (insideMacro()) { // Stack not empty
if (inputType == MACRO_ARGUMENT_STREAM) {
return END_OF_MACRO_ARGUMENT_EXCEPTION;
}
// Only free MACRO_STREAM buffers (allocated from macroBodyMemory)
if (inputType == MACRO_STREAM) {
mbmFreeUntil(currentInput.begin);
}
currentInput = macroInputStack[--macroStackIndex]; // Pop
}
else if (inputType == NORMAL_STREAM) {
// Refill from file
buildLexemFromCharacters(¤tFile.characterBuffer, ...);
}
}
11.2.3. Key Invariant
Stream type must match buffer allocation:
-
MACRO_STREAM→ buffer allocated frommacroBodyMemory -
NORMAL_STREAM→ buffer NOT from macro arenas -
MACRO_ARGUMENT_STREAM→ buffer fromppmMemory
Violating this invariant causes fatal errors when trying to free buffers from the wrong arena.
11.2.4. Common Bug Pattern
Pushing a NORMAL_STREAM onto the macro stack, then trying to free it as if it were MACRO_STREAM:
// WRONG: Blindly freeing without checking type
mbmFreeUntil(currentInput.begin); // Fails if currentInput is NORMAL_STREAM!
// CORRECT: Check type first
if (inputType == MACRO_STREAM) {
mbmFreeUntil(currentInput.begin);
}
11.3. How does …
TBD. == Development Environment
11.4. Developing, here be dragons…
First the code is terrible, lots of single and double character
variables (cc, ccc, ..) and lost of administration on local
variables rather than the structures that are actually there. And
there are also a lot of macros. Unfortunately macros are hard to
refactor to functions. (But I’m making progress…)
As there is no general way to refactor a macro to a function, various techniques must be applied. I wrote a blog post about one that have been fairly successful.
But actually it’s rather fun to be able to make small changes and see the structure emerge, hone your refactoring and design skills, and working on a project that started 20 years ago which still is valuable, to me, and I hope, to others.
There should probably be a whole section on how to contribute and
develop c-xrefactory but until then here’s a short list of what
you need:
-
C development environment (GNU/Clang/Make/…)
-
Unittests are written using
Cgreen -
Clean code and refactoring knowledge (to drive the code to a better and cleaner state)
Helpful would be:
-
Compiler building knowledge (in the general sense, Yacc, but AST:s and symbol table stuff are heavily used)
11.5. Setup
TBD.
11.6. Building
You should be able build c-xref using something like (may have changed over time…)
cd src make make unit make test
But since the details of the building process are somewhat contrieved and not so easy to see through, here’s the place where that should be described.
One step in the build process was generating initialization information
for all the things in standard include files, which of course became
very dependent on the system you are running this on. This has now moved
into functions inside c-xref itself, like finding DEFINEs and include
paths.
The initial recovered c-xrefactory relied on having a working c-xref for the current system. I don’t really know how they managed to do that for all the various systems they were supporting.
Modern thinking is that you should always be able to build from source, so this is something that needed change. We also want to distribute c-xref as an el-get library which requires building from source and should generate a version specific for the current system.
The strategy selected, until some better idea comes along, is to try to build a c-xref.bs, if there isn’t one already, from the sources in the repository and then use that to re-generate the definitions and rebuild a proper c-xref. See Bootstrapping.
We have managed to remove the complete bootstrapping step, so c-xrefactory
now builds like any other project.
11.7. Versions
The current sources are in 1.6.X range. This is the same as the orginal xrefactory and probably also the proprietary C++ supporting version.
There is an option, "-xrefactory-II", that might indicate that
something was going on. But currently the only difference seems to be
if the edit server protocol output is in the form of non-structured
fprintf:s or using functions in the ppc-family (either calling
ppcGenRecord() or `fprint`ing using some PPC-symbol). This, and
hinted to in how the emacs-part starts the server and some initial
server option variables in refactory.c, indicates that the
communication from the editor and the refactory server is using
this. It does not look like this is a forward to next generation
attempt.
What we should do is investigate if this switch actually is used anywhere but in the editor server context, and if so, if it can be made the default and the 'non-xrefactory-II' communication removed.
11.8. Coding
11.8.1. Naming
C-xref started (probably) as a cross-referencer for the languages supported (C, Java, C++), orginally had the name "xref" which became "xrefactory" when refactoring support was added. And when Mariàn released a "C only" version in 2009 most of all the "xref" references and names was changed to "c-xref". So, as most software, there is a history and a naming legacy to remember.
Here are some of the conventions in naming that are being used:
- olcx
-
"On-line CX" (Cross-reference) ?
- OLO
-
"On-line option" - some kind of option for the server
11.8.2. Modules and Include Files
The source code for c-xrefactory was using a very old C style with a
separate proto.h where all prototypes for all externally visible
functions were placed. Definitions are all over the place and it was
hard to see where data is actually declared. This must change into
module-oriented include-strategy.
Of course this will have to change into the modern x.h/x.c externally visible interface model so that we get clean modules that can be unittested.
The function prototypes have been now moved out to header files for each "module". Some of the types have also done that, but this is still a work in progress.
11.9. Debugging
TBD. Attachning gdb, server-driver…
yaccp from src/.gdbinit can ease the printing of Yacc semantic data fields…
A helpful option is the recently added -commandlog=… which allows
you to capture all command arguments sent to the server/xref process
to a file. This makes it possible to capture command sequences and
"replay" them. Useful both for debugging and creating tests.
11.9.1. Arena Allocator Lifetime Violations
The preprocessor macro expansion code uses arena allocators (ppmMemory, macroBodyMemory)
with stack-like discipline. Arena allocators are fast (pointer bumping) but require
careful lifetime management.
The Problem Pattern
Arena allocators can only resize the most recent allocation ("top-of-stack"). A common violation occurs when trying to resize a buffer after other allocations:
buffer = ppmAllocc(size); // Allocate buffer
marker = ppmAllocc(0); // Save marker for cleanup
temp = ppmAllocc(tempSize); // Allocate temporary
ppmReallocc(buffer, newSize, ...); // ❌ FAILS - buffer not at top!
ppmFreeUntil(marker); // Free temporaries
The correct pattern frees temporaries before growing the buffer:
buffer = ppmAllocc(size); // Allocate buffer
marker = ppmAllocc(0); // Save marker
temp = ppmAllocc(tempSize); // Allocate temporary (use it)
ppmFreeUntil(marker); // Free temporaries FIRST
ppmReallocc(buffer, newSize, ...); // ✅ Works - buffer now at top
Lifetime Violation Guards
The arena allocator includes guards that catch lifetime violations with detailed diagnostics:
- Guard 1: Buffer Resize Guard (
memory.cinmemoryRealloc()) -
Checks buffer is at top-of-stack before resizing. Provides expected vs actual locations and suggests moving
ppmFreeUntil()earlier. - Guard 2: FreeUntil Bounds Guard (
memory.cinmemoryFreeUntil()) -
Ensures marker is within valid allocated range. Catches corrupted or wrong-arena markers.
- Guard 3: Top-of-Stack Helper (
memoryIsAtTop()) -
Allows explicit verification before operations requiring top-of-stack:
assert(memoryIsAtTop(&ppmMemory, buffer, oldSize)); ppmReallocc(buffer, newSize, sizeof(char), oldSize);
Example: test_collation_long_expansion
This test case triggered the violation guard when macro expansion created a very large
output (19 FLAG_STRING invocations). The collate() function was calling ppmFreeUntil()
after copyRemainingLexems(), which needed to grow the caller’s buffer.
The fix: move ppmFreeUntil() to before copyRemainingLexems(). By this point,
temporary allocations from macro expansion were already used and could be freed,
allowing the buffer to become top-of-stack again.
Debugging With Guards
When a guard triggers:
-
Read the fatal error messages - they explain what went wrong
-
Look for the assertion location in the stack trace
-
Check if
ppmFreeUntil()is being called too late -
Verify buffer growth happens after temporaries are freed
The guards turn subtle crashes into clear diagnostics that point to the fix.
11.10. Testing
11.10.1. Unittests
There are very few unittests at this point, only covering single digit percent of the code. The "units" in this project are unclear and entangled so creating unittests is hard since it was not build to be tested, test driven or even clearly modularized.
All unittests use Cgreen as the unittest framework. If you are
unfamiliar with it the most important point is that it can mock
functions, so you will find mock implementations of all external
functions for a module in a corresponding <module>.mock file.
Many modules are at least under test, meaning there is a <module>_tests.c in the unittest directory. Often only containing an empty test.
11.10.2. Acceptance Tests
In the tests directory you will find tests that exercise the external
behaviour of c-xref. Some tests actually do only that, they wouldn’t
really count as tests.
Most acceptance tests are hacks at this point, Make-scripts tweaked until it produces some expected output. But at least they get the coverage up (working our way up to the mid 60%), and more are added as bugs are found so they provide increasing confidence when developing.
There are two basic strategies for the tests:
-
run a
c-xrefcommand, catch its output and verify -
run a series of command using the EDIT_SERVER_DRIVER, collect output and results and verify
Some tests do not even test its output and only provide coverage.
Some tests do a very bad job at verifying, either because my understanding at that time was very low, or because it is hard to verify the output. E.g. the "test" for generate references are only grepping the CXrefs files for some strings, not verifying that they actually point to the correct place.
Hopefully this will change as the code gets into a better state and the understanding grows.
11.10.3. General Setup
Since all(?) c-xref operation rely on an options file which must
contain absolute file paths (because the server runs as a separate
process) it must be generated whenever the tests are to be run in a
different location (new clone, test was renamed, …).
This is performed by using a common template in tests and a target
in tests/Maefile.boilerplate.
Each test should have a clean target that removes any temporary and
generated files, including the .c-xrefrc file and generated
references. This way it is easy to ensure that all tests have updated
.c-xrefrc files.
11.10.4. Edit Server Driver Tests
Since many operations are performed from the editor, and the editor starts an "edit server" process, many tests need to emulate this behaviour.
The edit server session is mostly used for navigation. Refactorings
are actually performed as separate invocations of c-xref.
In utils there is a server_driver.py script, which will take as
input a file containing a sequence of commands. You can use this to
start an edit, refactory or reference server session and then feed it
with commands in the same fashion as an editor would do. The script
also handles the communication through the buffer file (see [Editor
Interface](./Design:-Editor-Interface)).
11.10.5. Creating More Edit Server Tests
You can relatively easy re-create a sequence of interactions by using the
sandboxed Emacs in tests/sandboxed_emacs.
There are two ways to use it, "make spy" or "make pure". With the "spy" an intermediate spy is injected between the editor and the edit server, capturing the interaction to a file.
With "pure" you just get the editor setup with c-xref-debug-mode and
c-xref-debug-preserve-tmp-files on. This means that you can do what
ever editor interactions you want and see the communication in the
*Messages* buffer. See [Editor Interface](./Design:-Editor-Interface)
for details.
Once you have figure out which part of the *Messages* buffer are
interesting you can copy that out to a file and run
utils/messages2commands.py on it to get a file formatted for input
to server_driver.py.
the messages2commands script converts all occurrences of the
current directory to CURDIR so it is handy to be in the same directory
as the sources when you run the conversion.
|
the messages2commands script removes any -preload so you
need to take care that the positions inside the buffers are not
changed between interactions lest the -olcursor and -olmark will
be wrong. (You can just undo the change after a refactoring or
rename). Of course this also applies if you want to mimic a sequence
of refactorings, like the jexercise move method example. Sources will
then change so the next refactoring works from content of buffers, so you
have to handle this specifically.
|
-preload is the mechanism where the editor can send modified
buffers to c-xref so thay you don’t have to save between
refactorings, which is particularly important in the case of extract
since the extraction creates a default name which the editor then does
a rename of.
|
11.11. Utilities
11.11.1. Covers
utils/covers.py is a Python script that, in some enviroments, can list which test cases execute a particular line.
This is handy when you want to debug or step through a particular part of the code.
Find a test that covers that particular line and run it using the debugger (usually make debug in the test directory).
Synopsis:
covers.py <file> <line>
11.11.2. Sandboxed
utils/sandboxed starts a sandboxed Emacs that uses the current elisp code and the c-xref from src.
This allows you to run a test changes without having to polute your own setup.
This actually runs the tests/sandboxed_emacs pure version, which also sets up a completely isolated Emacs environment with its own packages loaded, configuration etc.
See below.
Synopsis:
sandboxed
11.12. Debugging the protocol
There is a "pipe spy" in tests/sandboxed_emacs. You can build the
spy using
make spy
and then start a sandboxed Emacs which invokes the spy using
make
This Emacs will be sandboxed to use its own .emacs-files and have HOME set to this directory.
The spy will log the communication between Emacs and the real
c-xref (src/c-xref) in log files in /tmp.
NOTE that Emacs will invoke several instanced of what it believes is
the real c-xref so there will be several log files to inspect.
12. Deployment
TBD.
13. Decision Log
This chapter provides a historical record of significant design and architectural decisions made during the evolution of c-xrefactory.
13.1. Overview
The decision log documents choices that have shaped the architecture, implementation, and direction of c-xrefactory. Most decisions from the original 1990s development are lost to history, but as they can be deduced from the codebase and commit history, they are being retroactively documented.
All architectural decisions are recorded using the Architecture Decision Record (ADR) format and stored in the adr/ directory. These ADRs are automatically integrated into the Structurizr documentation system.
13.2. Viewing Decision Records
The ADRs can be accessed in several ways:
-
Via Structurizr: When viewing the Structurizr documentation, navigate to the "Decisions" section to see all ADRs with cross-references and visualizations.
-
Directly in the repository: Browse the adr/ directory for markdown files containing individual decision records.
-
Command line: Use
ls doc/adr/*.mdfrom the project root to list all decisions.
13.3. Decision Categories
Current ADRs cover several categories:
-
Simplification decisions: Removing unused features (Java support, HTML generation, etc.)
-
Tooling decisions: Choice of ADR format, documentation system
-
Configuration decisions: Automatic config file discovery
-
Format decisions: Reference data storage format
For the complete list of decisions and their rationale, see the ADR directory or the Decisions section in the Structurizr documentation.
13.4. Creating New ADRs
When making significant architectural decisions:
-
Copy the template from
adr/templates/ -
Number it sequentially (e.g.,
0012-description.md) -
Fill in the context, decision, and consequences
-
Commit it alongside the implementation
-
Reference it in commit messages and pull requests
See ADR-0007 for details on the ADR format and process.
14. Roadmap
This chapter outlines the development roadmap for c-xrefactory, tracking completed work, current priorities, and future architectural goals.
14.1. Guiding Principles
The roadmap is guided by these principles:
-
Incremental improvement: Each step should provide immediate value while moving toward long-term goals
-
Test-driven modernization: Maintain ~80% test coverage to enable confident refactoring
-
Backward compatibility: Preserve existing Emacs workflows while enabling modern IDE integration
-
Architectural simplification: Replace artificial mode distinctions with unified, smart on-demand behavior
-
Legacy code respect: Work with the existing 1990s codebase thoughtfully, not against it
14.2. Recent Accomplishments (2025 Q1)
14.2.1. C Preprocessor Compliance Fixes
Problem: c-xrefactory was incorrectly expanding function-like macros during token pasting, violating C99 §6.10.3.3 which mandates that operands of should NOT be macro-expanded before concatenation.
Impact: Caused SIGSEGV in test_ffmpeg when processing complex standard library macros like INT64_MAX which expands to (INT64_C(9223372036854775807)) where INT64_C(c) is defined as c ## L.
Fix: Removed macro expansion logic from collate() function in src/yylex.c:1749-1797. Now matches GCC behavior exactly.
Test Updates: Updated 5 test cases to match correct GCC preprocessor behavior:
-
test_collate_empty -
test_token_pasting_with_expansion -
test_token_pasting_with_expansion_lhs -
test_token_pasting_with_expansion_rhs -
test_token_pasting_with_illegal_expansion
14.2.2. Memory Scaling Improvements
Problem: Large projects like ffmpeg were hitting the 30MB stackMemory limit during symbol table construction.
Root Cause: Stack memory is a persistent arena allocator that accumulates symbol tables across all parsed files. Growth is expected and normal for large projects.
Fix: Increased SIZE_stackMemory from 30MB to 100MB in src/constants.h:19.
Diagnostic Additions: Added nesting level and stack index tracking in src/xref.c to monitor memory usage patterns and detect unbalanced block nesting.
14.3. Short-term Goals (Next 3-6 Months)
14.3.1. Test Coverage Expansion
Current Status: ~80% coverage, ongoing improvement
Priority: HIGH
Goals:
-
Achieve 85%+ coverage for core modules
-
Add focused tests for macro expansion subsystem
-
Expand coverage for LSP integration points
-
Systematic testing of error handling paths
14.3.2. LSP Feature Completeness
Current Status: Basic LSP communication works, features not yet accessible
Priority: HIGH
Goals:
-
Wire up existing symbol navigation to LSP protocol
-
Implement
textDocument/definitionusing reference database -
Implement
textDocument/references -
Implement
textDocument/hoverwith symbol information -
Enable
textDocument/completionfor basic completion
Approach: Leverage existing reference database (refTab) and symbol tables - no major architectural changes needed initially.
14.3.3. Documentation Completeness
Current Status: Architecture documentation mostly complete
Priority: MEDIUM
Goals:
-
Complete Structurizr C4 model with all major components
-
Document memory management strategies across all arenas
-
Create user guide for LSP integration
-
Document LSP vs Emacs feature parity matrix
14.4. Medium-term Goals (6-12 Months)
These goals are detailed in Chapter 16: Proposed Refactorings. The roadmap establishes priority ordering:
14.4.1. 1. LexemStream API Improvements
Priority: HIGH (Foundation for other refactorings)
Rationale: The macro expansion code suffers from pointer parameter proliferation (6+ parameters per function). Adding a manipulation API to LexemStream (similar to LexemBuffer) will simplify buffer management and reduce error-prone pointer arithmetic.
Impact:
-
Reduces
collate()from 6 parameters to 3-4 -
Centralizes buffer management logic
-
Enables clearer ownership semantics
-
Foundation for macro module extraction
Estimated Effort: 3-4 weeks
-
Week 1: Design and implement core API
-
Week 2: Refactor
copyRemainingLexems()andcollate()as proof-of-concept -
Week 3-4: Migrate remaining macro expansion functions
14.4.2. 2. Extract Macro Expansion Module
Priority: MEDIUM (Depends on LexemStream API)
Rationale: yylex.c is 2353 lines combining lexing, file management, preprocessor directives, and macro expansion (~800 lines). Extracting macro expansion improves modularity and testability.
Impact:
-
Reduces yylex.c by 34% (~800 lines)
-
Enables independent testing of macro expansion
-
Clearer separation: lexing vs. preprocessing
-
Facilitates future C++ macro support
Estimated Effort: 4-6 weeks
-
Week 1-2: Create module structure and move memory management
-
Week 3-4: Migrate token processing and expansion logic
-
Week 5-6: Integration, testing, and documentation
14.4.3. 3. Unified Symbol Database Architecture
Priority: HIGH (Enables true on-demand LSP)
Rationale: Current artificial distinction between "file-based" and "on-demand" modes creates unnecessary complexity. Both Emacs and LSP clients want the same thing: up-to-date symbol information.
Key Insight: The .cx files are a persistent cache of analysis results, not a fundamental requirement. c-xrefactory should provide smart on-demand behavior that:
-
Always ensures information is current using existing dependency tracking
-
Scans incrementally only what’s needed, when needed
-
Uses
.cxfiles for optimization, not as a prerequisite
Impact:
-
Eliminates cold start - no upfront
-createrequired -
Single code path for Emacs and LSP
-
Transparent caching -
.cxfiles automatically maintained -
Leverages existing logic - reuses proven dependency tracking system
Architecture:
Symbol* lookupSymbol(const char* name, Position pos) {
// 1. Check if cached information is up-to-date
if (symbolInfoIsCurrent(name, pos)) {
return getCachedSymbolInfo(name, pos);
}
// 2. Use existing dependency tracking to scan minimal set
FileList* filesToScan = calculateDependencyClosure(pos.file);
for (FileItem* file : filesToScan) {
if (checkFileModifiedTime(file->fileNumber)) {
scanFileAndUpdateCache(file);
}
}
// 3. Update persistent cache
updateSymbolCache(name, pos);
return getSymbolInfo(name, pos);
}
Estimated Effort: 8-12 weeks
-
Week 1-3: Design unified interface and wrap existing logic
-
Week 4-6: Implement smart dependency-driven on-demand scanning
-
Week 7-9: Optimize caching strategies and incremental updates
-
Week 10-12: Thorough testing, performance tuning, documentation
14.5. Long-term Vision (12-24 Months)
14.5.1. On-Demand Incremental Architecture for LSP
Current Limitation: Stack memory accumulates symbol tables across all files forever. This works for batch cross-referencing but is incompatible with long-running LSP servers handling file edits.
Vision: Enable true on-demand, per-file parsing suitable for LSP textDocument/didChange events.
Two-Phase Architecture
Phase 1: Batch Indexing (Current behavior, optimized)
For each file in project:
Parse file → populate refTab → discard stackMemory symbols
Result: refTab contains all references, stackMemory reset between files
Phase 2: LSP On-Demand (Future capability)
Load refTab from .cx files (persistent cache)
On textDocument/didChange(file):
1. Remove old references for file from refTab
2. Reparse file → update refTab with new references
3. Reset stackMemory (symbols discarded, only refTab persists)
4. Navigation uses refTab, not stackMemory symbols!
Key Architectural Insights
-
Navigation uses refTab, not stackMemory: This is crucial - symbol lookup queries the reference table, not the ephemeral symbol structures
-
stackMemory can be reset per-file: As long as refTab is updated first
-
Incremental file updates become possible: Parse → update refTab → discard symbols
-
Backward compatible: Batch mode continues to work exactly as before
Memory Management Strategy
After unified symbol database is complete, investigate:
-
Per-file stackMemory reset after populating refTab
-
Separation of navigation data (refTab - persistent) from parsing data (stackMemory - ephemeral)
-
Smart arena allocation strategies for long-running servers
-
Background garbage collection for unused symbol data
Estimated Effort: 16-20 weeks (major architectural work)
14.5.2. Full LSP Protocol Compliance
Dependencies: Unified symbol database, on-demand architecture
Goals:
-
Complete implementation of core LSP features:
-
textDocument/definition✓ (basic navigation exists) -
textDocument/references✓ (reference database exists) -
textDocument/hover(symbol information) -
textDocument/completion✓ (completion system exists) -
textDocument/rename✓ (refactoring engine exists) -
textDocument/documentSymbol(symbol outline) -
textDocument/formatting(if desired) -
workspace/symbol(project-wide symbol search)
-
-
Performance optimization for large projects:
-
Lazy loading of symbol data
-
Incremental parsing on file changes
-
Background indexing
-
Memory-mapped
.cxfile access
-
-
Multi-workspace support
-
Configuration via LSP initialization options
Estimated Effort: 20-24 weeks (building on unified database)
14.5.3. Modern IDE Integration Showcase
Dependencies: Full LSP compliance
Goals:
-
VS Code Extension: Official c-xrefactory extension with feature parity to Emacs
-
Vim/Neovim Support: LSP client configuration and documentation
-
Other IDEs: Ensure LSP implementation works with CLion, Qt Creator, etc.
-
Feature Demonstrations: Video tutorials showing refactoring capabilities
-
Benchmark Comparisons: Performance vs. clangd, ccls for large C codebases
Marketing:
-
Emphasize unique C-specific features (macro understanding, Yacc support)
-
Highlight safe refactoring capabilities
-
Target embedded systems and legacy C projects
14.6. Migration and Compatibility Strategy
14.6.1. Backward Compatibility Guarantee
-
Existing Emacs workflows will continue to work unchanged
-
.cxfile format remains compatible (or auto-migrates transparently) -
Command-line interface preserved (though some commands may become no-ops)
-
All existing refactoring operations maintain behavior
14.6.2. Deprecation Path
When unified symbol database is complete:
-
-createbecomes optional (auto-triggers on first query if needed) -
-updatebecomes automatic (modification time checking) -
Mode flags (
FILE_BASED,ON_DEMAND) deprecated internally -
User-visible options remain for backward compatibility but may have no effect
14.6.3. Testing Strategy
Throughout all changes:
-
Zero test regressions - 140+ test suite must pass
-
Coverage maintenance - keep ~80%+ coverage during refactoring
-
Performance validation - no >5% regression on large projects
-
Integration testing - both Emacs and LSP workflows tested
14.7. Success Metrics
14.7.1. Technical Metrics
-
Test Coverage: Maintain 80%, target 85%
-
Response Time: LSP
textDocument/definition< 100ms for 90th percentile -
Memory Efficiency: LSP server < 500MB RAM for 1M LOC project
-
Startup Time: Zero cold start delay (no mandatory
-create)
14.7.2. Adoption Metrics
-
VS Code Extension: 1000+ downloads in first 6 months
-
GitHub Stars: 500+ (currently ~150)
-
Issue Response: <48 hours median time to first response
-
Documentation: 100% of features documented with examples
14.7.3. Community Metrics
-
Contributors: 5+ active contributors beyond maintainer
-
LSP Compatibility: Works with 3+ major IDEs (VS Code, Vim, CLion)
-
User Satisfaction: Positive feedback on LSP integration
14.8. Risk Management
14.8.1. Technical Risks
| Risk | Likelihood | Mitigation |
|---|---|---|
Breaking existing Emacs users |
Medium |
Maintain strict backward compatibility, extensive testing, staged rollout |
Performance regression |
Medium |
Profile before/after each change, performance test suite, optimization budget |
LSP protocol complexity |
Low |
Use existing battle-tested LSP libraries, focus on core features first |
Memory leaks in long-running server |
Medium |
Careful arena allocator design, memory profiling, leak detection tools |
Difficulty attracting contributors |
High |
Excellent documentation, beginner-friendly issues, responsive maintainer |
Competing with clangd |
High |
Focus on unique strengths: macro understanding, Yacc support, safe refactoring |
14.8.2. Mitigation Strategies
-
Incremental delivery: Each phase provides standalone value
-
Continuous testing: Never sacrifice test coverage for features
-
User feedback loops: Early LSP alpha with select users
-
Fallback options: Keep old code paths during transition
-
Documentation first: Write the docs before the code
14.9. Next Actions
Priority tasks for immediate action:
-
Complete LSP handler wiring (1-2 weeks)
-
Map existing navigation functions to LSP requests
-
Test with real LSP client (VS Code)
-
Document any gaps
-
-
Design LexemStream API (1 week)
-
Finalize interface based on proposal
-
Create initial implementation
-
Write unit tests
-
-
Plan unified database refactoring (2 weeks)
-
Detailed design document
-
Identify all affected code paths
-
Prototype dependency-driven scanning
-
-
Establish performance baseline (1 week)
-
Measure current Emacs operation speeds
-
Profile memory usage patterns
-
Document acceptable overhead budgets
-
14.10. Conclusion
The roadmap balances immediate user value (LSP features, bug fixes) with long-term architectural health (unified database, modular design). Each phase builds on previous work, with clear success metrics and risk mitigation strategies.
The end goal is a c-xrefactory that is:
-
Zero-configuration: Works immediately on any C project
-
Modern: First-class LSP support for all IDEs
-
Powerful: Unique C-specific features unmatched by competitors
-
Maintainable: Clean architecture enabling continued evolution
-
Backward compatible: Existing Emacs users unaffected
This transformation from a 1990s batch cross-referencer to a modern, on-demand LSP server is achievable through careful incremental refactoring guided by comprehensive tests.
| This roadmap is a living document. As priorities shift and new insights emerge, it will be updated to reflect current understanding and goals. See also Chapter 16: Proposed Refactorings for detailed technical proposals. |
15. Proposed Refactorings
This chapter documents larger refactoring proposals that would significantly improve code quality but require careful planning and implementation.
15.1. LexemStream API Improvements
15.1.1. Problem Statement
The macro expansion and collation code (collate(), replaceMacroArguments(), etc.) in src/yylex.c suffers from pointer parameter proliferation, making it difficult to understand and maintain. Functions pass 5-6 separate parameters to track buffer state:
static char *collate(char *buffer, int *bufferSizeP, char **bufferWriteP,
char **leftHandLexemP, char **rightHandLexemP,
LexemStream *actualArgumentsInput);
static void copyRemainingLexems(char *buffer, int *bufferSize, char **bufferWriteP,
char *nextLexemP, char *endOfInputLexems);
This creates several issues:
-
Hard to track which pointers point into which buffers
-
Manual size/capacity management scattered throughout code
-
Easy to make mistakes with pointer arithmetic
-
Functions have 6+ parameters just for buffer management
15.1.2. Current Architecture
Three representations of lexem streams
The codebase currently uses three different ways to represent lexem streams:
- LexemBuffer (structured, file-oriented)
-
-
Fixed-size embedded array:
char lexemStream[LEXEM_BUFFER_SIZE] -
Metadata:
begin,read,write,position,fileOffset,backpatchPointer -
Used for lexing from files/editor buffers
-
Full API for manipulation:
putLexemCode(),getLexemCode(), etc.
-
- LexemStream (lightweight, pointer-based)
-
-
Just 3 pointers + metadata:
begin,read,write,macroName,inputType -
Points to external memory (doesn’t own it)
-
Used for macro expansion pipelines
-
NO manipulation API - just raw pointer access
-
- MacroBody (persistent storage)
-
-
Pointer + length:
char *body,int size -
Used for stored macro definitions
-
LexemStream buffer sources
LexemStream can point to 5 different memory sources:
-
LexemBuffer.lexemStream- Fixed array in file descriptor -
ppmAlloc()- Preprocessor macro memory (dynamic) -
mbmAlloc()- Macro body memory (dynamic) -
NULL- Empty/missing arguments -
External buffers from various sources
15.1.3. Proposed Solution
Add LexemStream manipulation API
Currently, LexemStream has zero manipulation functions. All operations are done via raw pointer manipulation. We need to add an API similar to LexemBuffer.
Phase 1: Extend LexemStream structure
Add optional buffer management fields:
typedef struct {
char *begin; // Start of buffer
char *read; // Current read position
char *write; // Current write position (= end for read-only)
char *macroName; // Name of macro this input represents
InputType inputType;
// NEW fields:
int allocatedSize; // Total allocated size (0 if not owned/unknown)
bool ownsBuffer; // Whether this LexemStream should manage/free the buffer
} LexemStream;
Alternative considered but rejected: Create separate WritableLexemStream type. Pro: Cleaner separation of read vs write. Con: Yet another type, conversion overhead, more complex API.
|
Phase 2: Create manipulation API
New file: src/lexinput.c and extend src/input.h
Core buffer management
// Creation
LexemStream lexInputCreateOwned(int initialSize); // Allocates managed buffer
LexemStream lexInputCreateView(char *begin, char *end); // Read-only view
// Capacity management
void lexInputEnsureCapacity(LexemStream *input, int additionalBytes);
void lexInputReallocIfNeeded(LexemStream *input, int needed);
int lexInputRemainingCapacity(LexemStream *input);
// Reading (advance read pointer)
LexemCode lexInputGetLexem(LexemStream *input);
LexemCode lexInputPeekLexem(LexemStream *input); // Don't advance
bool lexInputHasMore(LexemStream *input); // read < write
void lexInputSkipLexem(LexemStream *input); // Skip current lexem
// Writing (advance write pointer)
void lexInputPutLexemCode(LexemStream *output, LexemCode lexem);
void lexInputPutLexemPosition(LexemStream *output, Position pos);
void lexInputAppendBytes(LexemStream *dest, char *src, int len);
void lexInputCopyLexem(LexemStream *dest, LexemStream *src); // Copy one lexem from src to dest
// Cleanup
void lexInputFree(LexemStream *input); // Only frees if ownsBuffer=true
Phase 3: Refactor functions to use LexemStream API
Example: collate() before
static char *collate(char *buffer, // Destination buffer
int *bufferSizeP, // Destination allocated size
char **bufferWriteP, // Current write position
char **leftHandLexemP, // Left operand read position
char **rightHandLexemP, // Right operand read position
LexemStream *actualArgumentsInput) // Source arguments
{
// Manual buffer management scattered throughout:
*bufferSizeP = expandPreprocessorBufferIfOverflow(buffer, *bufferSizeP, *bufferWriteP);
// Manual pointer arithmetic:
int lexemLength = nextInputLexemP - lexemStart;
memcpy(*bufferWriteP, lexemStart, lexemLength);
*bufferWriteP += lexemLength;
// Complex state tracking:
char *lhs = *leftHandLexemP;
char *endOfLexems = NULL;
// ... many lines of pointer manipulation
}
Example: collate() after
static void collate(LexemStream *output, // Destination (manages its own buffer)
LexemStream *leftOperand, // Left operand (with read position)
LexemStream *rightOperand, // Right operand (with read position)
LexemStream *actualArgumentsInput)
{
// Clean, high-level operations:
lexInputEnsureCapacity(output, estimatedSize);
// Copy operations are explicit and clear:
lexInputCopyLexem(output, leftOperand);
lexInputCopyLexem(output, rightOperand);
// State is encapsulated in LexemStream structures
}
Functions to refactor (priority order)
-
collate() - Most complex, biggest win (yylex.c:1515)
-
copyRemainingLexems() - Used by collate (yylex.c:1450)
-
resolveMacroArgumentAsLeftOperand() - Complex pointer tracking (yylex.c:1465)
-
replaceMacroArguments() - Many buffer operations (yylex.c:1717)
-
expandMacroArgument() - Buffer management (yylex.c:1362)
-
createMacroBodyAsNewInput() - Multiple buffers (yylex.c:1780)
15.1.4. Benefits
Code clarity
-
Functions have 2-3 parameters instead of 6+
-
Clear ownership and boundaries
-
Self-documenting code (LexemStream instead of 3 raw pointers)
Maintainability
-
Centralized buffer management logic
-
Easier to add bounds checking
-
Less error-prone
Consistency
-
Similar philosophy to LexemBuffer
-
Uniform API for lexem stream operations
15.1.5. Implementation Strategy
- Step 1: Add new fields to LexemStream (backward compatible)
-
-
Initialize
allocatedSize = 0andownsBuffer = falsefor all existing uses -
No functional changes yet
-
- Step 2: Create lexinput.c with basic API
-
-
Implement core functions: create, ensure capacity, append, copy
-
Add unit tests
-
- Step 3: Refactor one function as proof of concept
-
-
Start with
copyRemainingLexems()(simplest) -
Validate approach works
-
- Step 4: Refactor remaining functions
-
-
Work through priority list
-
Update call sites incrementally
-
- Step 5: Cleanup
-
-
Remove old helper functions if no longer needed
-
Update documentation
-
15.1.6. Risks and Mitigation
Risk: Breaking existing code
Mitigation:
-
Make LexemStream changes backward compatible
-
Add new fields with safe defaults
-
Refactor incrementally, one function at a time
-
Run full test suite after each change
Risk: Performance regression
Mitigation:
-
Keep buffer operations inline where critical
-
Profile before/after
-
The current code already does realloc, just manually
Risk: Memory leaks from ownsBuffer confusion
Mitigation:
-
Clear ownership semantics in documentation
-
Consider using explicit create/destroy pairs
-
Add assertions for debugging
15.1.7. Notes
Why not unify with LexemBuffer?
LexemBuffer and LexemStream serve different purposes:
-
LexemBuffer: Heavy, file-oriented, owns fixed-size array, lots of metadata
-
LexemStream: Lightweight, flexible views, points to various sources
Trying to unify them would make both worse. The real issue is LexemStream lacks manipulation functions, not that two types exist.
Backward compatibility
The proposed changes are designed to be backward compatible:
-
New fields default to "not owned, size unknown" (0, false)
-
Existing code that creates LexemStream with
makeLexemStream()continues to work -
Only new code uses the enhanced API
15.1.8. Open Questions
-
Should
lexInputEnsureCapacity()use ppmAlloc or mbmAlloc?-
Probably depends on context - may need separate functions or a memory source parameter
-
-
How to handle the transition from raw pointers to LexemStream?
-
Some functions receive raw pointers from outside (e.g., from MacroBody.body)
-
May need wrapper functions to create temporary LexemStream views
-
-
Should we add debug assertions for bounds checking?
-
Would help catch errors during development
-
Could be compiled out in production
-
15.1.9. References
-
Current code:
src/yylex.clines 1362-1823 (macro expansion) -
LexemBuffer API:
src/lexembuffer.handsrc/lexembuffer.c -
Current LexemStream:
src/input.handsrc/input.c
15.1.10. Related Issues
This refactoring addresses the root cause identified in the discussion about replacing the malloc-based macro body memory system (commit e1d506f7). The memory tracking issues stem from the complexity of managing multiple pointer parameters across function boundaries.
| When implementing this refactoring, consider starting with unit tests for the new API functions before refactoring existing code. This will help validate the design and provide safety during migration. |
15.2. Unified Symbol Database Architecture
15.2.1. Problem Statement
The current symbol database has evolved from a batch cross-referencer (like ctags) with artificial distinctions between "file-based" and "on-demand" modes. This creates:
-
Mode complexity: Different code paths for Emacs vs LSP clients
-
Cold start problems: Requires upfront
-createoperation before use -
Manual updates: Users must remember to run
-updateafter changes -
Inconsistent behavior: Different modes provide different guarantees
-
Maintenance overhead: Multiple implementations to maintain and test
15.2.2. Current Architecture Limitations
The existing system distinguishes between:
| Aspect | File-Based Mode | On-Demand Mode |
|---|---|---|
Cold Start |
Requires |
Parse file immediately |
Warm Queries |
O(1) hash lookup |
O(file_size) parsing |
Memory Usage |
Low (streaming) |
High (in-memory cache) |
Incremental Updates |
Smart file tracking |
Per-file invalidation |
Multi-project |
Separate databases |
Workspace-scoped |
15.2.3. Proposed Solution
Core Insight: Unified On-Demand Architecture
Both Emacs and LSP clients want the same thing: up-to-date symbol and reference information. The distinction between "file-based" and "on-demand" modes is artificial complexity. Instead, c-xrefactory should provide a unified interface that:
-
Always ensures information is current using existing dependency tracking
-
Scans incrementally only what’s needed, when needed
-
Uses
.cxfiles as persistent cache for optimization -
Eliminates cold start problems by avoiding upfront full-project scanning
Simplified Interface Design
typedef struct SymbolDatabase SymbolDatabase;
typedef struct {
// Unified operations for any client (Emacs or LSP)
Symbol* (*lookupSymbol)(SymbolDatabase* db, const char* name, Position pos);
ReferenceList* (*getReferences)(SymbolDatabase* db, const char* name, Position pos);
ReferenceList* (*getOccurrences)(SymbolDatabase* db, const char* name, Position pos);
// All complexity hidden in implementation:
// - File modification checking (existing: checkFileModifiedTime)
// - Include dependency tracking (existing: cachedIncludedFilePass)
// - Incremental scanning (existing: makeIncludeClosureOfFilesToUpdate)
// - Persistent caching (existing: .cx file system)
} SymbolDatabaseOperations;
Implementation Strategy: Smart On-Demand
The implementation leverages existing sophisticated logic:
Symbol* lookupSymbol(const char* name, Position pos) {
// 1. Check if cached information is up-to-date
if (symbolInfoIsCurrent(name, pos)) {
return getCachedSymbolInfo(name, pos); // Use .cx files when valid
}
// 2. Use existing dependency tracking to scan minimal set
FileList* filesToScan = calculateDependencyClosure(pos.file);
for (FileItem* file : filesToScan) {
if (!checkFileModifiedTime(file->fileNumber)) {
scanFileAndUpdateCache(file); // Incremental scan
}
}
// 3. Update persistent cache for next time
updateSymbolCache(name, pos);
return getSymbolInfo(name, pos);
}
Key Benefits:
-
No artificial modes - same code path for all clients
-
No cold start - first lookup triggers minimal necessary scanning
-
Incremental by design - only scans files that need updating
-
Persistent optimization - results cached in
.cxfiles for next session -
Existing logic reuse - leverages proven dependency tracking system
Legacy Architecture Recognition
c-xrefactory evolved from a batch cross-referencer (like ctags) and was enhanced for real-time use:
# Legacy batch workflow:
c-xref -create project.c # Full scan, build .cx database
c-xref -update modified.c # Incremental update
c-xref -olcxpush symbol # Query pre-built database
# Unified approach:
c-xref -server # Start server, scan on-demand as needed
c-xref -lsp # Same logic, different protocol
The .cx files are essentially a persistent cache of analysis results, not a fundamental requirement.
15.2.4. Implementation Plan
Phase 1: Interface Unification
-
Create unified
SymbolDatabaseinterface -
Wrap existing logic in smart on-demand implementation
-
Replace explicit
-create/-updatecommands with automatic dependency checking -
Both Emacs and LSP use same code path
Phase 2: Optimization
-
Enhance existing dependency tracking for finer-grained invalidation
-
Optimize in-memory caching strategies
-
Background
.cxfile maintenance for long-running sessions -
Performance tuning for large codebases
15.2.5. Benefits
Architectural Simplification
-
Single code path for both Emacs and LSP clients - eliminates maintenance overhead
-
No mode distinctions - same smart logic serves all use cases optimally
-
Leverages existing logic - reuses proven dependency tracking and caching systems
-
Reduced complexity - eliminates artificial FILE_BASED/ON_DEMAND/HYBRID modes
User Experience Improvements
-
Zero configuration - works immediately on any C project without setup
-
No cold start delay - first symbol lookup triggers minimal necessary scanning
-
Transparent caching -
.cxfiles automatically maintained as performance optimization -
Consistent behavior - same results whether using Emacs or modern IDE with LSP
Performance Characteristics
-
Minimal initial cost - avoids expensive upfront full-project scanning
-
Smart incremental updates - only rescans files that have actually changed
-
Automatic dependency tracking - includes files affected by changes get updated
-
Persistent optimization - analysis results cached across sessions
Development Benefits
-
Backward compatibility - existing Emacs workflows continue unchanged
-
Forward compatibility - natural path to modern LSP integration
-
Reduced maintenance - single implementation instead of multiple modes
-
Enhanced testability - unified logic easier to test comprehensively
15.2.6. Existing Infrastructure
Sophisticated Dependency Tracking
The unified approach leverages c-xrefactory’s existing sophisticated dependency management that handles include file relationships automatically:
File Modification Tracking (filetable.h):
typedef struct fileItem {
char *name;
time_t lastModified; // Last known modification time
time_t lastInspected; // Last time we checked
time_t lastUpdateMtime; // Last update cycle time
time_t lastFullUpdateMtime; // Last full update time
// ... scheduling and state flags
} FileItem;
bool checkFileModifiedTime(int fileNumber);
Include Dependency Tracking (yylex.c):
void pushInclude(FILE *file, EditorBuffer *buffer, char *name, char *prepend) {
// ... setup include stack
includeStack.stack[includeStack.pointer++] = currentFile;
// Track include relationships for dependency analysis
}
Automatic Include Closure (xref.c:81-108):
static void makeIncludeClosureOfFilesToUpdate(void) {
// If file A includes file B, and B is modified, A gets scheduled for update
// This uses the reference database to track include relationships
bool fileAddedFlag = true;
while (fileAddedFlag) {
// Iterative closure: keeps adding dependent files until stable
for (all scheduled files) {
find_all_files_that_include_this_file();
schedule_them_for_update();
}
}
}
| This dependency tracking infrastructure is already production-ready and handles the complex cases (transitive dependencies, modification time checking, include stack management). The unified symbol database can leverage this existing logic instead of reimplementing dependency management. |
15.2.7. Open Questions
-
Should we maintain backward compatibility with explicit
-create/-updatecommands?-
Probably yes, at least as no-ops or aliases to make transition easier
-
-
How to handle very large projects (>1M LOC)?
-
May need workspace-level configuration for incremental scanning thresholds
-
Consider lazy loading of symbol data
-
-
What’s the migration path for existing users?
-
Existing
.cxfiles should continue to work -
Auto-migrate on first run with new version
-
Provide clear documentation on new behavior
-
15.2.8. References
-
Current implementation:
src/cxfile.c,src/xref.c -
File tracking:
src/filetable.h,src/filetable.c -
Dependency tracking:
src/xref.clines 81-108 -
Current database description: See chapter 08 (Code) - Reference Database section
15.3. Extract Macro Expansion Module
15.3.1. Problem Statement
The yylex.c file is 2353 lines and combines multiple responsibilities:
-
Lexical analysis and token reading
-
File and buffer management
-
Preprocessor directive processing
-
Macro expansion system (~800 lines)
The macro expansion code is a substantial, cohesive subsystem that would benefit from extraction into its own module. Currently, it’s deeply embedded in yylex.c, making both lexing and macro expansion harder to understand and test in isolation.
15.3.2. Current Architecture
The macro expansion system in yylex.c comprises:
Core Responsibilities (~800 lines)
-
Macro call expansion - Main orchestration (
expandMacroCall()) -
Argument processing - Collection and recursive expansion
-
Token collation -
##operator implementation -
Stringification -
#operator implementation -
Memory management - Separate arenas for macro bodies (MBM) and arguments (PPM)
-
Cyclic detection - Preventing infinite macro recursion
Key State
int macroStackIndex; // Current macro expansion depth
static LexemStream macroInputStack[MACRO_INPUT_STACK_SIZE];
static Memory macroBodyMemory; // Long-lived: macro definitions
static Memory macroArgumentsMemory; // Short-lived: expansion temporaries
Memory Lifetime Separation
The system uses two distinct memory arenas with different lifetimes:
-
MBM (Macro Body Memory): Persistent storage for macro definitions throughout compilation
-
PPM (PreProcessor Memory): Temporary storage for expansion, collation, and argument processing
This separation is fundamental and should be preserved in any refactoring.
15.3.3. Proposed Solution
Extract macro expansion into a new module: macroexpansion.c/h
Public Interface
The new module would expose a minimal, focused API:
// Initialization
void initMacroExpansion(void);
int getMacroBodyMemoryIndex(void);
void setMacroBodyMemoryIndex(int index);
// Core expansion
bool expandMacroCall(Symbol *macroSymbol, Position position);
bool insideMacro(void);
int getMacroStackDepth(void);
// Memory allocation (exposed for macro definition processing)
void *macroBodyAlloc(size_t size);
void *macroBodyRealloc(void *ptr, size_t oldSize, size_t newSize);
void *macroArgumentAlloc(size_t size);
Module Boundaries
What moves to macroexpansion.c:
-
Macro call expansion and argument processing
-
Token collation (
collate()and helpers) -
Stringification (
macroArgumentsToString()) -
Cyclic call detection
-
MBM/PPM memory management
-
Buffer expansion utilities (
expandPreprocessorBufferIfOverflow(), etc.)
What remains in yylex.c:
-
Lexing and file input
-
Preprocessor directive processing (
#define,#ifdef, etc.) -
Include file handling
-
Main
yylex()function -
Macro symbol table operations
Dependencies:
The macro module would depend on:
-
Lexem stream operations (reading/writing)
-
Symbol lookup (
findMacroSymbol()) -
Cross-referencing (for collation and expansion references)
-
Current input state (via accessor functions)
15.3.4. Benefits
Architectural
-
Separation of concerns: Lexing vs. preprocessing clearly separated
-
Reduced file size: yylex.c drops from 2353 → ~1550 lines (34% reduction)
-
Testability: Macro expansion can be unit tested independently
-
Clearer ownership: Macro state and memory management centralized
Maintainability
-
Focused modules: Each file has a single, clear purpose
-
Easier reasoning: Macro behavior isolated from lexer concerns
-
Better documentation: Module-level documentation for macro system
Future flexibility
-
Could support different macro systems (C vs. C++)
-
Easier to add macro debugging/tracing
-
Independent optimization of macro expansion
15.3.5. Implementation Strategy
Phase 1: Preparation (Already Complete)
✓ Create LexemBufferDescriptor type for buffer management
✓ Refactor buffer expansion functions to use descriptor
✓ Eliminate return values for size updates
Phase 2: Create Module Structure
-
Create
macroexpansion.hwith public interface -
Create
macroexpansion.cwith initial implementations -
Move
LexemBufferDescriptorto appropriate header -
Create accessor functions for
currentInputstate
Phase 3: Incremental Function Migration
Move functions in this order (lowest risk first):
-
Memory management - MBM/PPM allocation functions
-
Buffer expansion -
expandPreprocessorBufferIfOverflow(),expandMacroBodyBufferIfOverflow() -
Support utilities -
cyclicCall(),prependMacroInput() -
Token processing -
collate(),resolveMacroArgument(), etc. -
Core expansion -
expandMacroCall(),createMacroBodyAsNewStream(), etc.
Phase 4: Integration and Cleanup
-
Update yylex.c to use new interface
-
Run full test suite after each migration step
-
Add focused unit tests for macro expansion
-
Update build system
-
Document the new architecture
15.3.6. Risks and Mitigation
Risk: Complex dependencies
Mitigation:
-
Create clear accessor functions for shared state
-
Use incremental approach - one function group at a time
-
Validate with tests after each step
Risk: Performance overhead
Mitigation:
-
Keep critical functions inline where necessary
-
Profile before/after migration
-
Current code already has abstraction layers
Assessment: Low risk - macro operations are complex enough that function call overhead is negligible
Risk: Breaking existing tests
Mitigation:
-
Run test suite after every migration step
-
Keep interface behavior identical
-
Use compiler to catch interface mismatches
15.3.7. Success Metrics
-
All existing tests pass
-
yylex.c reduced to ~1550 lines
-
New focused tests for macro expansion added
-
No performance regression (< 5% overhead acceptable)
-
Code review confirms improved clarity
15.3.8. Open Questions
-
Should
findMacroSymbol()move to the macro module or stay in yylex.c?-
It’s used by both lexer (for expansion triggering) and macro module (for nested expansions)
-
Probably belongs in a shared location or as part of symbol table operations
-
-
How to handle
currentInputglobal state?-
Options: Pass explicitly, use accessor functions, or provide context structure
-
Accessor functions likely cleanest:
getCurrentInput(),setCurrentInput()
-
-
Should we extract preprocessor directives at the same time?
-
No - keep changes focused
-
Could be a future refactoring after macro extraction proves successful
-
15.3.9. References
-
Current code:
src/yylex.clines 1327-2089 (macro expansion system) -
Memory management:
src/memory.h,src/memory.c -
Symbol operations:
src/symbol.h -
Related refactoring: LexemStream API Improvements addresses buffer management patterns
| This refactoring is independent of the LexemStream API improvements but would benefit from them being completed first, as they simplify buffer management patterns throughout the macro expansion code. |
16. Insights
This chapter contains notes of all insights, large and small, that I make as I work on this project. These insights should at some point be moved to some other, more structured, part of this document. But rather than trying to find a structure where each new finding fits, I’m making it easy to just dump them here. We can refactor these into a better and better structure as we go.
16.1. Yacc semantic data
As per usual a Yacc grammar requires each non-terminal to have a type.
Those types are named after which types of data they collect and
propagate. The names always starts with ast_ and then comes the
data type. For example if some non-terminal needs to propagate a
Symbol and a Position that structure would be called
ast_symbolParameterPair ("Pair" being thrown in there for good
measure…).
Each of those structures also always carries a begin and end position
for that structure. That means that any "ast" struct has three
fields, begin, end and the data. The data are sometimes a struct,
like in this case, but can also be a single value, like an int or a
pointer to a Symbol.
Failed to generate image: Could not load PlantUML. Either require 'asciidoctor-diagram-plantuml' or specify the location of the PlantUML JAR(s) using the 'DIAGRAM_PLANTUML_CLASSPATH' environment variable. Alternatively a PlantUML binary can be provided (plantuml-native in $PATH).
class ast_symbolPositionPair {
Position begin
Position end
}
ast_symbolPositionPair *-- SymbolPositionPair : data
class SymbolPositionPair {
Symbol *symbol
Position position
}
17. Archive
In this section you can find some descriptions and saved texts that described how things were before. They are no longer true, since that quirk, magic or bad coding is gone. But it is kept here as an archive for those wanting to do backtracking to original sources.
17.1. Memory strategies
There were a multitude of specialized memory allocation functions. In principle there where two types, static and dynamic. The dynamic could be exteded using a overflow handler.
Also one type had a struct where the actual area was extended beyond the actual struct. This was very confusing…
17.1.1. Static memory allocation
Static memory (SM_ prefix) are static areas allocated by the compiler
which is then indexed using a similarly named index variable
(e.g. ftMemory and ftMemoryIndex), something the macros took
advantage of. These are
-
ftMemory -
ppmMemory -
mbMemory
One special case of static memory also exist:
-
stackMemory- synchronous with program structure and has CodeBlock markers, so there is a specialstackMemoryInit()that initializes the outermost CodeBlock
These areas cannot be extended, when it overruns the program stops.
17.2. Trivial Prechecks
The refactorer can call the server using parseBufferUsingServer() and add some extra options (in text form).
One example is setMovingPrecheckStandardEnvironment() where it calls the server with -olcxtrivialprecheck.
However parseBufferUsingServer() uses callServer() which never answerEditAction().
In answerEditAction() the call to (unused) olTrivialRefactoringPreCheck() also requires an options.trivialPreCheckCode which is neither send by setMovingPrecheckStandardEnvironment() nor parsed by processOptions().
The only guess I have is that previously all prechecks where handled by the -olcxtrivialprecheck option in calls to the server, and have now moved to their respective refactorings.
| This theory should be checked by looking at the original source of the precheck functions and compare that with any possible checks in the corresponding refactoring code. |
17.3. HUGE Memory
Previously a HUGE model was also available (by re-compilation) to reach file numbers, lines and columns above 22 bits. But if you have more than 4 million lines (or columns!) you should probably do something radical before attempting cross referencing and refactoring.
17.4. Bootstrapping
17.4.1. BOOTSTRAP REMOVED!
Once the FILL-macros was removed, we could move the enum-generation to
use the actual c-xref. So from now on we build c-xref directly
from the sources in the repo. Changes to any enums will trigger a
re-generation of the enumTxt-files but since the enumTxt-files are
only conversion of enum values to strings any mismatch will not
prevent compilation, and it would even be possible to a manual
update. This is a big improvement over the previous situation!
17.4.2. FILLs REMOVED!
As indicated in FILL macros the bootstrapping of FILL-macros has finally and fully been removed.
Gone is also the compiler_defines.h, which was just removed without
any obvious adverse effects. Maybe that will come back and bite me
when we move to more platforms other than linux and MacOS…
Left is, at this point, only the enumTxt generation, so most of the
text below is kept for historical reasons.
17.4.3. Rationale
c-xref uses a load of structures, and lists of them, that need to be created and initialized in a lot of places (such as the parsers). To make this somewhat manageable, c-xref itself parses the strucures and generates macros that can be used to fill them with one call.
c-xref is also bootstrapped into reading in a lot of predefined header files to get system definitions as "preloaded definitions".
Why this pre-loading was necessary, I don’t exactly know. It might be an optimization, or an idea that was born early and then just kept on and on. In any case it creates an extra complexity building and maintaining and to the structure of c-xref.
So this must be removed, see below.
17.4.4. Mechanism
The bootstrapping uses c-xref's own capability to parse C-code and parse those structures and spit out filling macros, and some other stuff.
This is done using options like `-task_regime_generate' which prints a lot of data structures on the standard output which is then fed into generated versions of strFill, strTdef(no longer exists) and enumTxt by the Makefile.
The process starts with building a c-xref.bs executable from checked in sources. This compile uses a BOOTSTRAP define that causes some header files to include pre-generated versions of the generated files (currently strFill.bs.h and enumTxt.bs.h) which should work in all environments.
| if you change the name of a field in a structure that is subject to FILL-generation you will need to manually update the strFill.bs.h, but a "make cleaner all" will show you where those are. |
After the c-xref.bs has been built, it is used to generate strFill and enumTxt which might include specific structures for the current environment.
HOWEVER: if FILL macros are used for structures which are different on some platforms, say a FILE structure, that FILL macro will have difference number of arguments, so I’m not sure how smart this "smart" generation technique actually is.
TODO: Investigate alternative approaches to this generate "regime", perhaps move to a "class"-oriented structure with initialization functions for each "class" instead of macros.
17.4.5. Compiler defines
In options.h there are a number of definitions which somehow are sent to the compiler/preprocessor or used so that standard settings are the same as if a program will be compiled using the standard compiler on the platform. At this point I don’t know exactly how this conversion from C declarations to compile time definitions is done, maybe just entered as symbols in one of the many symboltables?
Typical examples include "__linux" but also on some platforms things like "fpos_t=long".
I’ve implemented a mechanism that uses "gcc -E -mD" to print out and
catch all compiler defines in compiler_defines.h. This was necessary
because of such definitions on Darwin which where not in the
"pre-programmed" ones.
TODO?: As this is a more general approach it should possibly
completely replace the "programmed" ones in options.c?
17.4.6. EnumTxt generation REMOVED!
To be able to print the string values of enums the module generate.c (called when regime was RegimeGenerate) could also generate string arrays for all enums. By replacing that with some pre-processor magic for the few that was actually needed (mostly in log_trace() calls) we could do away with that whole "generate" functionality too.
(Last commit with enum generation intact is https://github.com/thoni56/c-xrefactory/commit/aafd7b1f813f2c17c684ea87ac87a0be31cdd4c4.)
17.4.7. enumTxt
For some cases the string representing the value of an Enum is needed.
c-xref handles this using the "usual" 'parse code and generate' method.
The module generate.c does this generation too.
17.4.8. Include paths
Also in options.h some standard-like include paths are added, but there is a better attempt in getAndProcessGccOptions() which uses the compiler/preprocessor itself to figure out those paths.
TODO?: This is much better and should really be the only way, I think.
17.4.9. Problems
Since at bootstrap there must exist FILL-macros with the correct field
names this strategy is an obstacle to cleaning up the code since every
field is referenced in the FILL macros. When a field (in a structure
which are filled using the FILL macro) changes name, this will make
initial compilation impossible until the names of that field is also
changed in the strFill.bs.h file.
One way to handle this is of course to use c-xrefactory itself and
rename fields. This requires that the project settings also include a
pass with BOOTSTRAP set, which it does.
17.4.10. Removing
I’ve started removing this step. In TODO.org I keep a hierarchical list of the actions to take (in a Mikado kind of style).
The basic strategy is to start with structures that no other structure
depends on. Using the script utils/struct2dot.py you can generate a
DOT graph that shows those dependencies.
Removal can be done in a couple of ways
-
If it’s a very small structure you can replace a call to a
FILL_XXX()macro with a compound literal. -
A better approach is usually to replace it with a
fillXXX()function, or even better, with anewXXX(), if it consistently is preceeded with an allocation (in the same memory!). To see what fields vary you can grep all such calls, make a CSV-file from that, and compare all rows.
17.4.11. strTdef.h
The strTdef.h was generated using the option -typedefs as a part
of the old -task_regime_generate strategy and generated typedef
declarations for all types found in the parsed files.
I also think that you could actually merge the struct definition with the typedef so that strTdef.h would not be needed. But it seems that this design is because the structures in proto.h are not a directed graph, so loops makes that impossible. Instead the typedefs are included before the structs:
#include "strTdef.h"
struct someNode {
S_someOtherNode *this;
...
struct someOtherNode {
S_someNode *that;
...
This is now ideomatically solved using the structs themselves:
struct someNode {
struct someOtherNode *this;
...
struct someOtherNode {
struct someNode *that;
...
17.5. FILL macros
The FILL macros are now fully replaced by native functions or some other, more refactoring-friendly, mechanism. Yeah!***
During bootstrapping a large number of macros named __FILL_xxxx is created. The intent is that you can fill a complete structure with one call, somewhat like a constructor, but here it’s used more generally every time a complex struct needs to be initialized.
There are even _FILLF_xxx macros which allows filling fields in sub-structures at the same time.
This is, in my mind, another catastrophic hack that makes
understanding, and refactoring, c-xrefactory such a pain. Not to
mention the extra bootstrap step.
I just discovered the compound literals of C99. And I’ll experiment with replacing some of the FILL macros with compound literals assignments instead.
FILL_symbolList(memb, pdd, NULL);
could become (I think):
memb = (SymbolList){.d = pdd, .next = NULL};
If successful, it would be much better, since we could probably get rid of the bootstrap, but primarily it would be more explicit about which fields are actually necessary to set.
17.6. Caching Module
The caching module described below has been archived as it is no longer part of the current architecture.
The caching module was part of the memory management strategy when memory was scarce. It allowed the system to detect out-of-memory situations, discard, flush and re-use memory during file processing.
17.7. Caching System Architecture
The caching system described below has been archived as it is no longer part of the current architecture.
The c-xrefactory included a sophisticated caching system that enabled incremental parsing by caching parsed input streams, parser state, and file modification tracking. This optimization allowed for faster re-analysis when only portions of source files had changed.
17.7.1. Core Design Principles
Cache Point Model: The system placed strategic snapshots of parser state at external definition boundaries (functions, global variables, etc.). When files were re-processed, the system could validate cache integrity, recover from cache points, and resume parsing only from the first changed definition onward.
Separation of Concerns: Recent refactoring had separated file tracking from cache validation:
-
updateFileModificationTracking()- Updated file timestamps without side effects -
isFileModifiedSinceCached()- Pure validation function for cache integrity
17.7.2. Key Components
Cache Point Management (caching.c):
-
placeCachePoint(bool)- Placed strategic parser state snapshots -
recoverFromCache()- Restored parser state from cache points -
recoverCachePointZero()- Reset to initial cache state
File Modification Tracking:
The FileItem structure maintained multiple timestamp fields for tracking file modification:
struct FileItem {
time_t lastModified; // File's actual modification time
time_t lastInspected; // When we last checked the file
// ... other fields
}
Input Stream Caching:
-
cacheInput()- Cached tokenized input from lexer -
cachingIsActive()- Checked if caching was currently enabled -
activateCaching()/deactivateCaching()- Controlled caching state
17.7.3. Parser Integration
C Parser Integration: Both C and Yacc parsers placed cache points after each external_definition, but only when not processing include files (includeStack.pointer == 0).
Parser-Specific Behavior:
-
C Parser: Full caching enabled with regular cache point placement
-
Yacc Parser: Explicitly deactivated caching via
deactivateCaching()but still placed strategic cache points -
Include Files: Cache points skipped during include processing
17.7.4. System Dependencies
The caching system was deeply integrated throughout the parsing pipeline:
| Component | Functions Used | Purpose |
|---|---|---|
|
|
Lifecycle control |
|
|
Input processing |
|
|
File tracking |
|
|
File management |
|
|
Cross-reference coordination |
|
|
C grammar integration |
|
|
Yacc grammar integration |
17.7.5. Performance Characteristics
Cache Hit Scenarios:
-
Full Cache Hit: No file modifications since last parse - parser state recovered from cache point zero with minimal re-processing
-
Partial Cache Hit: File modified after Nth definition - recovery from cache point N with re-parsing only from point of change onward
-
Cache Miss: File structure changed or timestamps invalid - full re-parse with new cache points placed
Optimization Benefits:
-
Memory usage scales with number of definitions, not file size
-
File modification checking minimizes unnecessary re-reads
-
Input stream caching reduces lexer overhead
-
Strategic cache point placement enables clean recovery at definition boundaries
17.8. Users
The -user option has now been removed, both in the tool and the
editor adaptors, and with it one instance of a hashlist, the
olcxTab, which now is a single structure, the sessionData.
There is an option called -user which Emacs sets to the frame-id. To
me that indicates that the concept is that for each frame you create
you get a different "user" with the c-xref server that you (Emacs)
created.
The jedit adapter seems to do something similar:
options.add("-user");
Options.add(s.getViewParameter(data.viewId));
Looking at the sources to find when the function
olcxSetCurrentUser() is called it seems that you could have
different completion, refactorings, etc. going on at the same time in
different frames.
Completions etc. requires user interaction so they are not controlled by the editor in itself only. At first glance though, the editor (Emacs) seems to block multiple refactorings and referencs maintenance tasks running at the same time.
This leaves just a few use cases for multiple "users", and I think it adds unnecessary complexity. Going for a more "one user" approach, like the model in the language server protocol, this could really be removed.