Fix HDL and Hack Assembly syntax highlighting and queries

- Fixed HDL highlights query syntax error with #match? predicate
- Replaced #match? with #any-of? for exact string matching
- Fixed Hack Assembly outline query invalid field name
- Improved HDL syntax highlighting with comprehensive patterns
- Added HDL bracket matching for all syntax types
- Fixed XML scope mismatch from text.xml to source.xml
- Enhanced outline queries for better code navigation
This commit is contained in:
2025-09-11 11:24:24 -04:00
commit c231dbfd27
133 changed files with 2792 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

161
CHANGELOG.md Normal file
View File

@@ -0,0 +1,161 @@
# Changelog
All notable changes to the Nand2Tetris Zed Extension will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2.0.0] - 2025-01-26
### Added
- **Complete Hack Assembly Language Support** (.asm files)
- Full tree-sitter grammar with syntax highlighting
- Support for A-instructions (`@value`, `@symbol`)
- Support for C-instructions (`dest=comp;jump`)
- Label declarations (`(LABEL)`)
- All predefined symbols (`R0-R15`, `SP`, `LCL`, `ARG`, `THIS`, `THAT`, `SCREEN`, `KBD`)
- User-defined symbols and variables
- Comment highlighting and toggling
- Code outline showing labels and sections
- **VM Language Support** (.vm files)
- Complete tree-sitter grammar for VM commands
- Stack arithmetic operations (`add`, `sub`, `neg`, `eq`, `gt`, `lt`, `and`, `or`, `not`)
- Memory access commands (`push`, `pop`) with all memory segments
- Program flow commands (`label`, `goto`, `if-goto`)
- Function commands (`function`, `call`, `return`)
- Memory segment highlighting (`argument`, `local`, `static`, `constant`, `this`, `that`, `pointer`, `temp`)
- Function and label outline navigation
- **Test Script Language Support** (.tst files)
- Tree-sitter grammar for nand2tetris test scripts
- Test commands (`load`, `output-file`, `compare-to`, `set`, `eval`, `output`)
- Simulation control (`tick`, `tock`, `ticktock`)
- Control flow structures (`repeat`, `while`)
- Variable references (`RAM[n]`, register names, pin names)
- Binary value highlighting (`%B1010101`)
- Format specification highlighting
- Bracket matching for control blocks
- **Compare/Output File Support** (.cmp, .out files)
- Tree-sitter grammar for tabular test result files
- Header row highlighting with column names
- Binary and decimal value highlighting
- Register and pin reference recognition
- Table structure visualization
- **Custom Tree-sitter Grammars**
- Built from scratch for Assembly, VM, Test Script, and Compare/Output languages
- Full Rust bindings for all custom grammars
- Comprehensive test suites for each grammar
- Complete Node.js package configurations
- **Enhanced Documentation**
- Comprehensive README with examples for all languages
- Development guide for contributors
- Troubleshooting section with common issues
- Grammar development guidelines
### Enhanced
- **Extended Language Coverage**
- Now supports all major nand2tetris file types
- Complete course workflow coverage from hardware to software
- Consistent syntax highlighting across all languages
- **Improved Editor Integration**
- Code outline support for all languages
- Bracket matching where applicable
- Smart indentation rules
- Comment toggling support (`Cmd+/` or `Ctrl+/`)
- **Better Error Handling**
- Robust grammar parsing with error recovery
- Clear error messages for common issues
- Comprehensive troubleshooting documentation
### Technical
- **Grammar Architecture**
- Four new custom Tree-sitter grammars
- Proper semantic token classification
- Efficient parsing with minimal conflicts
- Full compatibility with Zed's Tree-sitter integration
- **Build System**
- Complete Rust build configuration for all grammars
- Node.js bindings for development tools
- Automated testing and validation
- Cross-platform compatibility
## [1.1.0] - Previous Release
### Added
- HDL (Hardware Description Language) support
- Jack programming language support
- Basic syntax highlighting and bracket matching
- Code outline for HDL chips and Jack classes
### Technical
- Integration with external tree-sitter grammars
- Basic Zed extension configuration
## [1.0.0] - Initial Release
### Added
- Initial extension structure
- Basic HDL support
- Extension manifest and configuration
---
## Development Notes
### Version 2.0.0 Represents a Major Milestone
This release transforms the extension from basic HDL/Jack support to comprehensive coverage of the entire nand2tetris ecosystem. The addition of four custom Tree-sitter grammars makes this the most complete nand2tetris editor integration available.
### Custom Grammar Development
The custom grammars were developed specifically for this extension to ensure:
- Accurate parsing of nand2tetris language specifications
- Optimal performance in the Zed editor
- Comprehensive syntax highlighting
- Proper semantic token classification
- Future extensibility and maintenance
### Breaking Changes
- Extension ID and configuration may have changed
- New file type associations require extension reinstallation
- Grammar compilation requires Rust toolchain
### Compatibility
- Requires Zed editor with Tree-sitter support
- Requires Rust installed via rustup for grammar compilation
- Compatible with all nand2tetris course materials
- Supports both individual files and complete project structures
### Performance
- All grammars optimized for fast parsing
- Minimal memory footprint
- Efficient syntax highlighting queries
- Responsive editor integration
## Future Roadmap
### Potential Future Enhancements
- Language server integration for advanced IDE features
- Code formatting support
- Integration with nand2tetris simulation tools
- Snippet support for common patterns
- Debugging integration
- Project template support
### Community Contributions
We welcome contributions for:
- Grammar improvements and bug fixes
- Additional language features
- Documentation enhancements
- Test case additions
- Performance optimizations
---
For detailed technical information, see [DEVELOPMENT.md](DEVELOPMENT.md).
For usage instructions, see [README.md](README.md).

359
DEVELOPMENT.md Normal file
View File

@@ -0,0 +1,359 @@
# Nand2Tetris Zed Extension - Development Guide
This guide provides detailed information for developers working on or contributing to the Nand2Tetris Zed extension.
## Overview
The extension provides comprehensive language support for all nand2tetris course languages through custom Tree-sitter grammars and Zed language configurations.
## Architecture
### Extension Structure
```
nand2tetris-zed/
├── extension.toml # Main extension configuration
├── languages/ # Zed language configurations
│ ├── hdl/ # Hardware Description Language
│ ├── jack/ # Jack programming language
│ ├── hack-assembly/ # Hack Assembly language
│ ├── vm/ # Virtual Machine language
│ ├── test-script/ # Test Script language
│ └── compare-output/ # Compare/Output file format
├── grammars/ # Tree-sitter grammar sources
│ ├── hdl/ # External grammar (quantonganh)
│ ├── jack/ # External grammar (nverno)
│ ├── hack-assembly/ # Custom grammar
│ ├── vm/ # Custom grammar
│ ├── test-script/ # Custom grammar
│ └── compare-output/ # Custom grammar
└── examples/ # Test files for validation
```
### Language Support Levels
1. **HDL & Jack**: Use external, mature Tree-sitter grammars
2. **Assembly, VM, Test Script, Compare/Output**: Custom grammars built specifically for this extension
## Grammar Development
### Prerequisites
- **Rust** (installed via rustup)
- **Node.js** and npm
- **tree-sitter-cli**: `npm install -g tree-sitter-cli`
### Grammar Structure
Each custom grammar follows this structure:
```
grammars/[language]/
├── grammar.js # Grammar definition
├── tree-sitter.json # Tree-sitter configuration
├── package.json # npm package configuration
├── Cargo.toml # Rust package configuration
├── binding.gyp # Node.js binding configuration
├── src/ # Generated parser code
│ ├── parser.c # Generated C parser
│ ├── grammar.json # Generated grammar metadata
│ └── node-types.json # Generated node type definitions
├── bindings/ # Language bindings
│ └── rust/ # Rust bindings
│ ├── lib.rs # Library interface
│ └── build.rs # Build script
└── queries/ # Tree-sitter queries
└── highlights.scm # Syntax highlighting queries
```
### Creating a New Grammar
1. **Create directory structure**:
```bash
mkdir -p grammars/my-language/{bindings/rust,queries}
cd grammars/my-language
```
2. **Create `grammar.js`**:
```javascript
module.exports = grammar({
name: 'my_language',
rules: {
source_file: $ => repeat($._item),
_item: $ => choice(
$.comment,
// Add your language constructs here
),
comment: $ => token(seq('//', /.*/)),
},
extras: $ => [
/\s/,
$.comment
]
});
```
3. **Create configuration files**:
- `tree-sitter.json` (see existing examples)
- `package.json` (Node.js package)
- `Cargo.toml` (Rust package)
- `binding.gyp` (Node.js bindings)
4. **Generate parser**:
```bash
tree-sitter generate
```
5. **Create Rust bindings**:
- `bindings/rust/lib.rs`
- `bindings/rust/build.rs`
6. **Create highlighting queries**:
- `queries/highlights.scm`
7. **Test the grammar**:
```bash
tree-sitter test
tree-sitter parse test-file.ext
```
### Grammar Rules Best Practices
#### Token Naming
- Use snake_case for rule names
- Prefix internal rules with `_`
- Use semantic names that describe the construct
#### Rule Structure
```javascript
// Good: Clear semantic meaning
instruction: $ => choice(
$.a_instruction,
$.c_instruction
),
// Bad: Generic naming
thing: $ => choice(
$.type1,
$.type2
),
```
#### Comments and Whitespace
Always handle comments and whitespace properly:
```javascript
extras: $ => [
/\s/, // Whitespace
$.comment // Comments
],
```
#### String Tokens
Use `token()` for multi-character operators:
```javascript
// Good
if_goto: $ => token('if-goto'),
// Bad (can cause parsing issues)
if_goto: $ => 'if-goto',
```
## Language Configuration
Each language needs a `config.toml` file in `languages/[language]/`:
```toml
name = "Language Name"
grammar = "grammar_name"
scope = "source.language_name"
path_suffixes = ["ext"]
line_comments = ["// "]
block_comments = [["/*", "*/"]] # Optional
tab_size = 4
hard_tabs = false
```
### Highlighting Queries
Create `.scm` files that map grammar nodes to semantic tokens:
```scheme
; Comments
(comment) @comment
; Keywords
"function" @keyword.function
"return" @keyword.control
; Identifiers
(identifier) @variable
(function_name) @function
; Literals
(number) @constant.numeric
(string) @string
```
### Query Development Tips
1. **Check node types**: Use `tree-sitter parse --debug` to see actual node structure
2. **Test queries**: Use `tree-sitter highlight` to test highlighting
3. **Use semantic tokens**: Follow TextMate/LSP token conventions
4. **Prioritize specificity**: More specific queries override general ones
## Testing
### Grammar Testing
```bash
cd grammars/[language]
tree-sitter test # Run test suite
tree-sitter parse example.ext # Parse specific file
tree-sitter highlight example.ext # Test highlighting
```
### Integration Testing
1. Install extension as dev extension in Zed
2. Open test files and verify:
- Syntax highlighting works
- Bracket matching functions
- Code outline appears
- Indentation behaves correctly
### Example Files
Create comprehensive example files in `examples/` that cover:
- All language constructs
- Edge cases
- Common patterns
- Error conditions
## Common Issues and Solutions
### Grammar Generation Errors
**Empty string rules**:
```
Error: The rule contains an empty string
```
Solution: Remove empty alternatives or use `optional()`
**Invalid node types in queries**:
```
Query error: Invalid node type 'foo'
```
Solution: Check `src/node-types.json` for actual node names
### Highlighting Issues
**Tokens not highlighting**:
1. Verify node exists in `node-types.json`
2. Check query syntax
3. Ensure grammar generates expected nodes
**Conflicting highlights**:
- More specific queries take precedence
- Use `#match?` predicates for conditional highlighting
### Zed Integration Issues
**Extension not loading**:
1. Check `extension.toml` syntax
2. Verify all referenced grammars exist
3. Check Zed logs for specific errors
**Grammar compilation fails**:
1. Ensure Rust is installed via rustup
2. Check that all required files are present
3. Verify tree-sitter grammar generates successfully
## Contributing Guidelines
### Code Style
- Follow existing patterns in grammar definitions
- Use clear, semantic naming
- Add comprehensive comments
- Test thoroughly before submitting
### Documentation
- Update README.md for user-facing changes
- Update this guide for development changes
- Include example files for new languages
- Document any breaking changes
### Pull Request Process
1. Create feature branch
2. Implement changes with tests
3. Update documentation
4. Test in Zed environment
5. Submit PR with clear description
### Commit Messages
Use conventional commits:
```
feat: add support for new language construct
fix: resolve highlighting issue with comments
docs: update installation instructions
test: add comprehensive test cases
```
## Release Process
1. **Version Bump**: Update `extension.toml` version
2. **Test**: Verify all grammars compile and work in Zed
3. **Documentation**: Update README.md and CHANGELOG.md
4. **Tag**: Create git tag for version
5. **Publish**: Submit to Zed extension registry (when available)
## Performance Considerations
### Grammar Optimization
- Avoid excessive backtracking in rules
- Use `token()` for multi-character sequences
- Minimize conflicts between rules
- Profile with `tree-sitter parse --time`
### Query Optimization
- Use specific node patterns over generic ones
- Avoid complex predicates when possible
- Test query performance on large files
## Debugging
### Grammar Debugging
```bash
tree-sitter generate --debug
tree-sitter parse --debug-graph file.ext
tree-sitter test --debug
```
### Query Debugging
```bash
tree-sitter query queries/highlights.scm file.ext
tree-sitter highlight file.ext
```
### Zed Debugging
- Check `zed: open log` for extension errors
- Use `--foreground` flag for verbose logging
- Test with minimal example files
## Resources
- [Tree-sitter Documentation](https://tree-sitter.github.io/tree-sitter/)
- [Zed Extension Guide](https://zed.dev/docs/extensions)
- [Nand2Tetris Course Materials](https://www.nand2tetris.org)
- [TextMate Grammar Guide](https://macromates.com/manual/en/language_grammars)
## Support
For development questions or issues:
1. Check existing GitHub issues
2. Review this development guide
3. Test with minimal reproducible examples
4. Provide detailed error messages and logs
---
This extension represents a complete implementation of nand2tetris language support, demonstrating how to create comprehensive Tree-sitter grammars and integrate them into modern editors.

37
LICENSE Normal file
View File

@@ -0,0 +1,37 @@
MIT License
Copyright (c) 2025 Sean O'Connor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
This extension includes grammars and code from other projects:
HDL Grammar:
- Source: tree-sitter-hdl by Quan Tong (https://github.com/quantonganh/tree-sitter-hdl)
- License: MIT
Jack Grammar:
- Source: tree-sitter-jack by nverno (https://github.com/nverno/tree-sitter-jack)
- License: GPL-3.0-or-later
The extension is designed for educational use with the nand2tetris course:
- Course: "The Elements of Computing Systems" by Noam Nisan and Shimon Schocken
- Website: https://www.nand2tetris.org

492
README.md Normal file
View File

@@ -0,0 +1,492 @@
# Nand2Tetris Language Extension for Zed
Complete language support for the nand2tetris course in the Zed editor, providing syntax highlighting, parsing, and editor integration for all major nand2tetris file types.
## Supported Languages
- **HDL** (Hardware Description Language) - for describing digital circuits and chips
- **Jack** - the high-level programming language used in the software construction part
- **Hack Assembly** - the assembly language for the Hack computer platform
- **Hack Binary** - machine code files (.hack) with 16-bit binary instructions
- **VM Language** - the virtual machine intermediate language
- **Test Scripts** - for testing and simulation of hardware and software components
- **Compare/Output Files** - for test result comparison and output verification
- **XML** - compiler output files from Jack compiler
## Features
### HDL Support
- **Enhanced syntax highlighting** for chip declarations, pin definitions, and part instantiations
- **Array notation support** for `a[16]`, `out[0..7]`, and bit ranges
- **Boolean literal support** for `true` and `false` values in connections
- Recognizes HDL keywords: `CHIP`, `IN`, `OUT`, `PARTS`
- **Improved highlighting** for identifiers, numbers, comments, and operators
- **Complete bracket matching** for `{}`, `()`, and `[]`
- **Enhanced code outline** showing chip structure with better hierarchy
- Comment toggling with `Cmd+/` (or `Ctrl+/`)
- **Better indentation** support for nested structures
### Jack Support
- Full syntax highlighting for Jack language constructs
- Support for classes, methods, functions, constructors
- Recognizes all Jack keywords and built-in types
- Proper highlighting for control flow (`if`, `while`, `return`)
- Bracket matching and smart indentation
- Code outline showing class structure with methods and fields
- Comment support for both `//` and `/* */` style comments
- Special highlighting for built-in constants (`this`, `true`, `false`, `null`)
### Hack Assembly Support
- **Enhanced syntax highlighting** for A-instructions (`@value`, `@symbol`)
- **Comprehensive C-instruction highlighting** with dest, comp, and jump fields
- **Full support** for all computation operations and jump conditions
- **Label declaration highlighting** (`(LABEL)`) with proper bracket matching
- **Complete predefined symbol recognition** (`R0-R15`, `SP`, `LCL`, `ARG`, `THIS`, `THAT`, `SCREEN`, `KBD`)
- **User-defined variable and symbol support** with proper highlighting
- **Negative constant support** (`@-1`, `@-32768`)
- **Enhanced comment highlighting** (`// comment`)
- **Better code outline** showing labels, symbols, and control flow
- **Improved bracket matching** for parentheses in labels
### VM Language Support
- Syntax highlighting for all VM commands
- Stack arithmetic operations (`add`, `sub`, `neg`, `eq`, `gt`, `lt`, `and`, `or`, `not`)
- Memory access commands (`push`, `pop`) with all segments
- Program flow commands (`label`, `goto`, `if-goto`)
- Function commands (`function`, `call`, `return`)
- Memory segment highlighting (`argument`, `local`, `static`, `constant`, `this`, `that`, `pointer`, `temp`)
- Code outline showing function declarations and labels
### Test Script Support
- Syntax highlighting for test commands (`load`, `output-file`, `compare-to`, `set`, `eval`, `output`)
- Simulation control commands (`tick`, `tock`, `ticktock`)
- Control flow structures (`repeat`, `while`)
- Variable reference highlighting (`RAM[n]`, register names, pin names)
- Binary and format specification highlighting
- Bracket matching for control blocks
### Compare/Output File Support
- Tabular data formatting for test results
- Header row highlighting with column names
- Binary and decimal value highlighting
- Register and pin reference recognition
- Table structure visualization
## Changelog
### Version 2.3.0 - Individual Grammar Repositories
- **NEW**: All grammars now have individual GitHub repositories for better maintenance
- **NEW**: Complete language support for all 8 nand2tetris languages
- **IMPROVED**: More reliable grammar loading with external repositories
- **IMPROVED**: Better organization and dependency management
- **IMPROVED**: Easier updates and maintenance of individual grammars
### Version 2.1.0 - Enhanced HDL Support
- **NEW**: Array notation support (`a[16]`, `out[0..7]`, bit ranges)
- **NEW**: Boolean literal support (`true`, `false` in connections)
- **IMPROVED**: Enhanced syntax highlighting with better visual distinction
- **IMPROVED**: Complete bracket matching including `[]` for arrays
- **IMPROVED**: Better code outline and indentation support
- **FIXED**: Grammar parsing for complex HDL constructs
### Version 2.2.0 - Comprehensive Language Support
- **NEW**: Hack Binary support (`.hack` files) for machine code
- **NEW**: XML support (`.xml` files) for compiler output
- **IMPROVED**: Enhanced Hack Assembly highlighting and parsing
- **IMPROVED**: Better predefined symbol recognition
- **IMPROVED**: Negative constant support in assembly
- **IMPROVED**: Enhanced code outline for all languages
- **IMPROVED**: Better bracket matching across all file types
## Installation
### Prerequisites
- **Zed Editor** (latest version recommended)
- **Rust** installed via rustup (required for grammar compilation)
### Install Rust (if needed)
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
```
### Install Extension
1. **Install as dev extension**:
- In Zed: `Cmd+Shift+P``zed: install dev extension`
- Select the `nand2tetris-zed` directory
2. **Test the extension**:
- Open any `.hdl`, `.jack`, `.asm`, `.vm`, `.tst`, `.cmp`, or `.out` files
- Verify syntax highlighting appears
## Supported File Types
- `.hdl` files - HDL (Hardware Description Language)
- `.jack` files - Jack programming language
- `.asm` files - Hack Assembly language
- `.hack` files - Hack Binary machine code
- `.vm` files - VM (Virtual Machine) language
- `.tst` files - Test scripts for simulation and testing
- `.cmp` files - Compare files (expected test outputs)
- `.out` files - Output files (actual test results)
- `.xml` files - XML compiler output files
## Example Files
### HDL Example (`And.hdl`)
```hdl
/**
* And gate:
* out = 1 if (a == 1 and b == 1)
* 0 otherwise
*/
CHIP And {
IN a, b;
OUT out;
PARTS:
Nand(a=a, b=b, out=nandOut);
Not(in=nandOut, out=out);
}
```
### Jack Example (`Math.jack`)
```jack
class Math {
static Array twoToThe;
/** Initializes the library. */
function void init() {
var int i;
let twoToThe = Array.new(16);
let twoToThe[0] = 1;
let i = 1;
while (i < 16) {
let twoToThe[i] = twoToThe[i-1] + twoToThe[i-1];
let i = i + 1;
}
return;
}
function int multiply(int x, int y) {
var int sum, shiftedX;
let sum = 0;
let shiftedX = x;
// Implementation details...
return sum;
}
}
```
### Hack Assembly Example (`Add.asm`)
```asm
// Computes R0 = 2 + 3
@2
D=A
@3
D=D+A
@0
M=D
// Loop example with labels
@i
M=1
(LOOP)
@i
D=M
@10
D=D-A
@END
D;JGT
@i
M=M+1
@LOOP
0;JMP
(END)
@END
0;JMP
```
### VM Language Example (`SimpleAdd.vm`)
```vm
// Stack arithmetic operations
push constant 7
push constant 8
add
// Memory operations
push local 0
push local 1
add
pop local 2
// Function definition
function Math.multiply 2
push constant 0
pop local 0
label LOOP
push local 1
push constant 0
eq
if-goto END
push local 0
push argument 0
add
pop local 0
goto LOOP
label END
push local 0
return
```
### Test Script Example (`CPU.tst`)
```tst
load CPU.hdl,
output-file CPU.out,
compare-to CPU.cmp,
output-list time%S1.3.1 instruction%B0.16.0 pc%D0.5.0;
set instruction %B0011000000111001, // @12345
tick, output, tock, output;
set instruction %B1110110000010000, // D=A
tick, output, tock, output;
repeat 10 {
ticktock;
}
output;
```
### Compare File Example (`And.cmp`)
```
| a | b |out|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
```
## Grammar Sources and Credits
This extension uses the following Tree-sitter grammars:
### HDL Grammar
- **Source**: [tree-sitter-hdl](https://github.com/quantonganh/tree-sitter-hdl)
- **Author**: Quan Tong (@quantonganh)
- **License**: MIT
### Jack Grammar
- **Source**: [tree-sitter-jack](https://github.com/nverno/tree-sitter-jack)
- **Author**: nverno (@nverno)
- **License**: GPL-3.0-or-later
### Hack Assembly Grammar
- **Source**: Custom tree-sitter grammar (included in this extension)
- **License**: MIT
### VM Language Grammar
- **Source**: Custom tree-sitter grammar (included in this extension)
- **License**: MIT
### Test Script Grammar
- **Source**: Custom tree-sitter grammar (included in this extension)
- **License**: MIT
### Compare/Output File Grammar
- **Source**: Custom tree-sitter grammar (included in this extension)
- **License**: MIT
### Nand2Tetris Course
This extension supports the languages from:
- **Course**: "The Elements of Computing Systems" (nand2tetris)
- **Authors**: Noam Nisan and Shimon Schocken
- **Website**: [nand2tetris.org](https://www.nand2tetris.org)
- **Book**: "The Elements of Computing Systems: Building a Modern Computer from First Principles"
## Language Features
### Syntax Highlighting
All languages support comprehensive syntax highlighting with proper categorization of:
- Keywords and built-in types
- Identifiers and variables
- Numbers and literals (including binary values)
- Comments and documentation
- Operators and punctuation
- String and character literals
- Memory references and registers
- Labels and function names
### Code Structure
- **HDL**: Shows chip declarations, input/output pins, and part instantiations
- **Jack**: Shows class structure, methods, functions, and field declarations
- **Hack Assembly**: Shows labels, A-instructions, and C-instructions
- **VM**: Shows function declarations, labels, and command structure
- **Test Scripts**: Shows test blocks, repeat/while loops, and file operations
- **Compare/Output**: Shows tabular data structure with headers and values
### Editor Integration
- Bracket matching and auto-closing for `{}`, `()`, and `[]`
- Smart indentation based on language structure
- Comment toggling with standard shortcuts (`Cmd+/` or `Ctrl+/`)
- Code outline in the sidebar showing:
- HDL: Chip structures
- Jack: Class methods and fields
- Assembly: Labels and major sections
- VM: Functions and labels
- Test Scripts: Test blocks and file operations
- Compare/Output: Table structure
## Project Structure
This extension includes custom tree-sitter grammars for maximum compatibility:
```
nand2tetris-zed/
├── extension.toml # Extension configuration
├── README.md # This file
├── examples/ # Example files for testing
│ ├── test.asm # Hack Assembly example
│ ├── test.vm # VM language example
│ ├── test.tst # Test script example
│ └── test.cmp # Compare file example
├── languages/ # Language configurations
│ ├── hdl/ # HDL language config
│ ├── jack/ # Jack language config
│ ├── hack-assembly/ # Assembly language config
│ ├── vm/ # VM language config
│ ├── test-script/ # Test script config
│ └── compare-output/ # Compare/Output config
└── grammars/ # Tree-sitter grammars
├── hdl/ # External HDL grammar
├── jack/ # External Jack grammar
├── hack-assembly/ # Custom Assembly grammar
├── vm/ # Custom VM grammar
├── test-script/ # Custom Test Script grammar
└── compare-output/ # Custom Compare/Output grammar
```
## Development
### Grammar Development
The custom grammars are built with tree-sitter and include:
- `grammar.js` - Grammar definition
- `src/parser.c` - Generated parser
- `queries/highlights.scm` - Syntax highlighting queries
- `bindings/rust/` - Rust language bindings
- Full tree-sitter package configuration
### Building Grammars
To rebuild the grammars (requires tree-sitter-cli):
```bash
cd grammars/hack-assembly
tree-sitter generate
tree-sitter test
cd ../vm
tree-sitter generate
tree-sitter test
cd ../test-script
tree-sitter generate
tree-sitter test
cd ../compare-output
tree-sitter generate
tree-sitter test
```
## Troubleshooting
### No syntax highlighting appears
1. **Check file extension**: Ensure files have the correct extensions (`.hdl`, `.jack`, `.asm`, `.vm`, `.tst`, `.cmp`, `.out`) (lowercase)
2. **Check Zed logs**: `Cmd+Shift+P``zed: open log` → look for extension errors
3. **Verify Rust installation**: Run `rustc --version` (must be installed via rustup)
4. **Restart Zed**: Close and reopen Zed completely
5. **Try manual language selection**: `Cmd+Shift+P``editor: select language` → choose the appropriate language
### Grammar compilation fails
1. **Ensure Rust is from rustup**:
```bash
rustup --version
rustc --version
```
2. **Reinstall if needed**:
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
### Extension loading issues
1. **Check extension path**: Make sure you're selecting the root `nand2tetris-zed` directory
2. **Verify file structure**: Ensure all required files are present
3. **Check logs**: Look for specific error messages in Zed logs
## Expected Results
When the extension is working correctly, you should see:
- Colorized syntax for all supported file types (HDL, Jack, Assembly, VM, Test Scripts, Compare/Output)
- Keywords highlighted in one color, types in another
- Variables, functions, and properties with distinct colors
- Memory references and registers properly highlighted
- Binary values and numbers with appropriate colors
- Working bracket matching for all bracket types
- Code outline in the sidebar showing language-appropriate structure
- Comment toggling with `Cmd+/` or `Ctrl+/`
- Smart indentation when typing
## Use Cases
This extension is perfect for:
- **Students** taking the nand2tetris course
- **Educators** teaching computer architecture and systems programming
- **Developers** exploring low-level computing concepts
- **Anyone** interested in understanding how computers work from first principles
The extension supports all phases of the nand2tetris course:
- **Projects 1-3**: HDL development for logic gates, ALU, and memory
- **Project 4**: Assembly language programming
- **Project 5**: Computer architecture (with assembly testing)
- **Project 6**: Assembler development
- **Projects 7-8**: VM implementation and stack arithmetic
- **Projects 9-11**: High-level language (Jack) and compiler development
- **Project 12**: Operating system development
## Contributing
Contributions are welcome! Please feel free to:
- Report bugs or issues
- Suggest new features
- Improve documentation
- Submit pull requests
## License and Attribution
This extension is provided for educational use with the nand2tetris course materials.
### Extension License
This Zed extension code is available under the MIT License.
### Grammar Licenses
- **HDL Grammar**: MIT License (see [tree-sitter-hdl](https://github.com/quantonganh/tree-sitter-hdl))
- **Jack Grammar**: GPL-3.0-or-later (see [tree-sitter-jack](https://github.com/nverno/tree-sitter-jack))
- **Custom Grammars**: MIT License (Hack Assembly, VM, Test Script, Compare/Output)
### Acknowledgments
- **Quan Tong** for creating the HDL Tree-sitter grammar
- **nverno** for creating the Jack Tree-sitter grammar
- **Noam Nisan and Shimon Schocken** for the nand2tetris course and language specifications
- **The Zed team** for the excellent extension API and Tree-sitter integration
- **The tree-sitter community** for the parsing framework
---
**Happy computing from first principles!** 🎓✨
For more information about the nand2tetris course, visit [nand2tetris.org](https://www.nand2tetris.org).

20
examples/And.hdl Normal file
View File

@@ -0,0 +1,20 @@
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/01/And.hdl
/**
* And gate:
* out = 1 if (a == 1 and b == 1)
* 0 otherwise
*/
CHIP And {
IN a, b;
OUT out;
PARTS:
// Put your code here:
Nand(a=a, b=b, out=nandOut);
Not(in=nandOut, out=out);
}

View File

@@ -0,0 +1,107 @@
// Enhanced Hack Assembly Test File
// Demonstrates all the improved highlighting features
// Test A-instructions with various symbol types
@R0 // Virtual register
@R15 // Virtual register
@SP // Stack pointer
@LCL // Local pointer
@ARG // Argument pointer
@THIS // This pointer
@THAT // That pointer
@SCREEN // Screen memory map
@KBD // Keyboard memory map
@userVar // User-defined variable
@LOOP // User-defined label
// Test constants (including negative)
@0 // Zero
@1 // One
@-1 // Negative one
@32767 // Max positive
@-32768 // Min negative
@42 // Random positive
@-42 // Random negative
// Test C-instructions with all destination combinations
D=A // D register
A=M // A register
M=D // M register
MD=A // M and D
AM=D // A and M
AD=M // A and D
AMD=A // All three
// Test computation field operations
D=0 // Zero
D=1 // One
D=-1 // Negative one
D=D // D register
D=!D // Not D
D=-D // Negate D
D=D+1 // Increment D
D=D-1 // Decrement D
D=A // A register
D=!A // Not A
D=-A // Negate A
D=A+1 // Increment A
D=A-1 // Decrement A
D=M // M register
D=!M // Not M
D=-M // Negate M
D=M+1 // Increment M
D=M-1 // Decrement M
D=D+A // D plus A
D=D-A // D minus A
D=A-D // A minus D
D=D&A // D and A
D=D|A // D or A
D=D+M // D plus M
D=D-M // D minus M
D=M-D // M minus D
D=D&M // D and M
D=D|M // D or M
// Test jump conditions
D;JGT // Jump if greater than
D;JEQ // Jump if equal
D;JGE // Jump if greater or equal
D;JLT // Jump if less than
D;JNE // Jump if not equal
D;JLE // Jump if less or equal
D;JMP // Unconditional jump
// Test label declarations
(MAIN_LOOP)
(END_PROGRAM)
(ERROR_HANDLER)
// Test complex program structure
@MAIN_LOOP
D;JGT
@END_PROGRAM
0;JMP
(MAIN_LOOP)
@SCREEN
D=A
@pointer
M=D
@KBD
D=M
@END_PROGRAM
D;JEQ
@pointer
A=M
M=-1
@pointer
M=M+1
@MAIN_LOOP
0;JMP
(END_PROGRAM)
0;JMP

33
examples/EnhancedHDL.hdl Normal file
View File

@@ -0,0 +1,33 @@
/**
* Enhanced HDL Test File
* Demonstrates all the new highlighting features
*/
CHIP EnhancedTest {
// Array notation support
IN a[16], b[8], c;
OUT out[16], flag, result[4];
PARTS:
// Boolean literals in connections
Mux16(a=a, b=false, sel=c, out=temp);
// Bit range operations
Add16(a=a[0..7], b=b, out=out[0..7]);
Add16(a=a[8..15], b=false, out=out[8..15]);
// Complex array operations
Not16(in=a, out=notA);
And16(a=notA, b=true, out=result);
// Single bit operations
And(a=a[0], b=b[0], out=flag);
// Mixed operations with ranges
Mux4Way16(a=a[0..3], b=a[4..7], c=a[8..11], d=a[12..15],
sel=c, out=out[0..3]);
}

129
examples/Math.jack Normal file
View File

@@ -0,0 +1,129 @@
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/12/Math.jack
/**
* A library of commonly used mathematical functions.
* Note: Jack compilers implement multiplication and division using OS method calls.
*/
class Math {
static Array twoToThe;
/** Initializes the library. */
function void init() {
var int i;
let twoToThe = Array.new(16);
let twoToThe[0] = 1;
let i = 1;
while (i < 16) {
let twoToThe[i] = twoToThe[i-1] + twoToThe[i-1];
let i = i + 1;
}
return;
}
/** Returns the absolute value of x. */
function int abs(int x) {
if (x < 0) {
return -x;
}
else {
return x;
}
}
/** Returns the product of x and y.
* When a Jack compiler detects the multiplication operator '*' in the
* program's code, it handles it by invoking this method. In other words,
* the Jack expressions x*y and multiply(x,y) return the same value.
*/
function int multiply(int x, int y) {
var int sum, shiftedX, i;
let sum = 0;
let shiftedX = x;
let i = 0;
while (i < 16) {
if (~((y & twoToThe[i]) = 0)) {
let sum = sum + shiftedX;
}
let shiftedX = shiftedX + shiftedX;
let i = i + 1;
}
return sum;
}
/** Returns the integer part of x/y.
* When a Jack compiler detects the multiplication operator '/' in the
* program's code, it handles it by invoking this method. In other words,
* the Jack expressions x/y and divide(x,y) return the same value.
*/
function int divide(int x, int y) {
var int neg_x, neg_y;
var int q;
var int result;
let neg_x = x < 0;
let neg_y = y < 0;
let x = Math.abs(x);
let y = Math.abs(y);
if (y > x) {
return 0;
}
let q = Math.divide(x, y + y);
if ((x - ((q + q) * y)) < y) {
let result = q + q;
}
else {
let result = q + q + 1;
}
if (neg_x = neg_y) {
return result;
}
else {
return -result;
}
}
/** Returns the integer part of the square root of x. */
function int sqrt(int x) {
var int y, j;
var int approx;
var int approx_squared;
let y = 0;
let j = 7; // (16 / 2) - 1
while (~(j < 0)) {
let approx = y + twoToThe[j];
let approx_squared = approx * approx;
if (~(approx_squared > x) & (approx_squared > 0)) {
let y = approx;
}
let j = j - 1;
}
return y;
}
/** Returns the greater number. */
function int max(int a, int b) {
if (a > b) {
return a;
}
else {
return b;
}
}
/** Returns the smaller number. */
function int min(int a, int b) {
if (a < b) {
return a;
}
else {
return b;
}
}
}

106
examples/test.asm Normal file
View File

@@ -0,0 +1,106 @@
// Test Hack Assembly file for syntax highlighting
// This file demonstrates various Hack Assembly features
// Simple A-instruction with constant
@17
D=A
// A-instruction with symbol
@sum
M=D
// C-instruction with all parts: dest=comp;jump
@i
D=M
@LOOP
D;JGT
// Label declaration
(LOOP)
// Various computation operations
@sum
D=M
@i
D=D+M
@sum
M=D
// Memory operations
@R0
D=M
@temp
M=D
// Predefined symbols
@SP
M=M+1
@LCL
D=M
@ARG
M=D
// Screen and keyboard
@SCREEN
D=A
@KBD
M=M+1
// Complex computations
D=D+1
D=D-1
D=!D
D=-D
A=D+A
M=D&A
D=D|M
// Jump conditions
@END
0;JMP
@value
D=M
@POSITIVE
D;JGT
@ZERO
D;JEQ
@NEGATIVE
D;JLT
(POSITIVE)
// Positive value handling
@1
D=A
@result
M=D
@END
0;JMP
(ZERO)
// Zero value handling
@0
D=A
@result
M=D
@END
0;JMP
(NEGATIVE)
// Negative value handling
@-1
D=A
@result
M=D
(END)
// Infinite loop
@END
0;JMP
// Variable declarations (will be resolved by assembler)
@counter
@total
@average

5
examples/test.cmp Normal file
View File

@@ -0,0 +1,5 @@
| a | b | out |
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |

97
examples/test.tst Normal file
View File

@@ -0,0 +1,97 @@
// Test script file for syntax highlighting
// This file demonstrates various test script features
load CPU.hdl,
output-file CPU.out,
compare-to CPU.cmp,
// Set up output format
output-list time%S1.3.1 inM%D0.6.0 instruction%B0.16.0 reset%B2.1.2 outM%D1.6.0 writeM%B3.1.2 addressM%D1.5.1 pc%D0.5.0 DRegister[]%D1.7.1;
// Test A-instruction: @12345
set instruction %B0011000000111001,
tick, output, tock, output;
// Test C-instruction: D=A
set instruction %B1110110000010000,
tick, output, tock, output;
// Test memory access
set instruction %B0101101110100000, // @23456
tick, output, tock, output;
set instruction %B1110000111110000, // AD=A-D
tick, output, tock, output;
// Test RAM operations
set RAM[0] 256,
set RAM[1] 0,
set RAM[2] 100,
repeat 10 {
ticktock;
output;
}
// Test conditional operations
set instruction %B0000001111101011, // @1003
tick, output, tock, output;
set instruction %B1110001100001000, // M=D
tick, output, tock, output;
// Test jump operations
set instruction %B0000000000001110, // @14
tick, output, tock, output;
set instruction %B1110001100000100, // D;jlt
tick, output, tock, output;
// While loop test
while RAM[0] > 0 {
set RAM[0] RAM[0] - 1,
ticktock;
output;
}
// Reset test
set reset 1;
tick, output, tock, output;
set instruction %B0111111111111111, // @32767
set reset 0;
tick, output, tock, output;
// Binary instruction tests
set instruction %B1111110111100000, // A=M+1
tick, output, tock, output;
set instruction %B1110001100101000, // AM=D
tick, output, tock, output;
// Test all jump conditions
set instruction %B1110001100000001, // D;JGT
tick, output, tock, output;
set instruction %B1110001100000010, // D;JEQ
tick, output, tock, output;
set instruction %B1110001100000011, // D;JGE
tick, output, tock, output;
set instruction %B1110001100000100, // D;JLT
tick, output, tock, output;
set instruction %B1110001100000101, // D;JNE
tick, output, tock, output;
set instruction %B1110001100000110, // D;JLE
tick, output, tock, output;
set instruction %B1110001100000111, // D;JMP
tick, output, tock, output;
// Final output
output;
echo "Test completed successfully";

193
examples/test.vm Normal file
View File

@@ -0,0 +1,193 @@
// Test VM file for syntax highlighting
// This file demonstrates various VM language features
// Stack arithmetic operations
push constant 7
push constant 8
add
push constant 3
sub
neg
// Logical operations
push constant 1
push constant 0
eq
push constant 5
push constant 3
gt
push constant 2
push constant 2
lt
// Bitwise operations
push constant 15
push constant 3
and
push constant 12
push constant 5
or
not
// Memory access operations
push argument 0
push argument 1
add
pop local 0
push local 0
push constant 1
add
pop local 1
push static 0
push static 1
add
pop static 2
push this 0
push that 0
add
pop this 1
push pointer 0
push pointer 1
add
pop temp 0
push temp 0
push temp 1
add
pop temp 2
// Program flow commands
label LOOP_START
push local 0
push constant 0
eq
if-goto LOOP_END
push local 0
push constant 1
sub
pop local 0
goto LOOP_START
label LOOP_END
// Function declaration
function Math.multiply 2
push constant 0
pop local 0 // sum = 0
push constant 0
pop local 1 // i = 0
label MULTIPLY_LOOP
push local 1
push argument 1
eq
if-goto MULTIPLY_END
push local 0
push argument 0
add
pop local 0
push local 1
push constant 1
add
pop local 1
goto MULTIPLY_LOOP
label MULTIPLY_END
push local 0
return
// Function call
push constant 5
push constant 3
call Math.multiply 2
pop temp 0
// Another function with local variables
function Fibonacci.compute 3
push argument 0
push constant 2
lt
if-goto FIBO_BASE_CASE
push argument 0
push constant 1
sub
call Fibonacci.compute 1
pop local 0
push argument 0
push constant 2
sub
call Fibonacci.compute 1
pop local 1
push local 0
push local 1
add
return
label FIBO_BASE_CASE
push argument 0
return
// Main function
function Main.main 0
push constant 10
call Fibonacci.compute 1
pop temp 0
return
// Complex memory operations
push constant 8000
pop pointer 1 // that = 8000
push constant 0
pop that 0 // that[0] = 0
push constant 1
pop that 1 // that[1] = 1
push constant 16384
pop pointer 1 // that = screen base address
push constant -1
pop that 0 // blacken first word
// Array processing example
function Array.sum 3
push constant 0
pop local 0 // sum = 0
push constant 0
pop local 1 // i = 0
label SUM_LOOP
push local 1
push argument 1 // array length
eq
if-goto SUM_END
push argument 0 // array base
push local 1 // index
add
pop pointer 1 // that = array[i] address
push that 0 // array[i] value
push local 0 // current sum
add
pop local 0 // sum += array[i]
push local 1
push constant 1
add
pop local 1 // i++
goto SUM_LOOP
label SUM_END
push local 0 // return sum
return

39
extension.toml Normal file
View File

@@ -0,0 +1,39 @@
id = "nand2tetris"
name = "Nand2Tetris"
version = "2.3.0"
schema_version = 1
authors = ["Sean O'Connor <sean@soconnor.dev>"]
description = "Complete language support for nand2tetris course languages: HDL, Jack, Hack Assembly, VM, Test Scripts, Compare Output, Hack Binary, and XML"
repository = "https://github.com/soconnor0919/nand2tetris-zed"
[grammars.hdl]
repository = "https://github.com/quantonganh/tree-sitter-hdl"
rev = "main"
[grammars.jack]
repository = "https://github.com/nverno/tree-sitter-jack"
rev = "1a617413ea92c237bff4cbe7fa67eb3bf4425596"
[grammars.hack_assembly]
repository = "https://github.com/soconnor0919/tree-sitter-hack-assembly"
rev = "main"
[grammars.vm]
repository = "https://github.com/soconnor0919/tree-sitter-vm"
rev = "main"
[grammars.test_script]
repository = "https://github.com/soconnor0919/tree-sitter-test-script"
rev = "main"
[grammars.compare_output]
repository = "https://github.com/soconnor0919/tree-sitter-compare-output"
rev = "main"
[grammars.hack_binary]
repository = "https://github.com/soconnor0919/tree-sitter-hack-binary"
rev = "main"
[grammars.xml]
repository = "https://github.com/soconnor0919/tree-sitter-xml"
rev = "main"

View File

@@ -0,0 +1 @@
int main(void) { return 0; }

Submodule grammars/compare_output added at 51fd3069d1

BIN
grammars/compare_output.wasm Executable file

Binary file not shown.

Submodule grammars/hack_assembly added at 74f44fa77e

BIN
grammars/hack_assembly.wasm Executable file

Binary file not shown.

1
grammars/hack_binary Submodule

Submodule grammars/hack_binary added at d408c50827

BIN
grammars/hack_binary.wasm Executable file

Binary file not shown.

1
grammars/hdl Submodule

Submodule grammars/hdl added at 2199fdf1d3

BIN
grammars/hdl.wasm Executable file

Binary file not shown.

1
grammars/jack Submodule

Submodule grammars/jack added at 1a617413ea

BIN
grammars/jack.wasm Executable file

Binary file not shown.

1
grammars/test_script Submodule

Submodule grammars/test_script added at 909bf1dfe8

BIN
grammars/test_script.wasm Executable file

Binary file not shown.

1
grammars/vm Submodule

Submodule grammars/vm added at 615f50fc59

BIN
grammars/vm.wasm Executable file

Binary file not shown.

1
grammars/xml Submodule

Submodule grammars/xml added at 1e86bc6d16

BIN
grammars/xml.wasm Executable file

Binary file not shown.

View File

@@ -0,0 +1,5 @@
; Compare/Output file bracket matching
; No brackets are used in compare/output file syntax
; These files contain simple tabular data with pipe separators
; No nested structures or bracket pairs to match

View File

@@ -0,0 +1,6 @@
name = "Compare Output"
grammar = "compare_output"
scope = "source.compare_output"
path_suffixes = ["cmp", "out"]
tab_size = 2
hard_tabs = false

View File

@@ -0,0 +1,40 @@
; Compare/Output file syntax highlighting queries based on actual node types
; Header row elements
(header_row) @markup.heading
; Column names in headers
(column_name) @property
; Register names in headers (RAM[0], RAM[256], etc.)
(register_name) @variable.builtin
; Pin names in headers
(pin_name) @property
; Generic names in headers
(generic_name) @property
; Data values
(binary_value) @constant.numeric
(decimal_value) @constant.numeric
(register_reference) @variable
; Table structure
"|" @punctuation.delimiter
; Separator rows
(separator_row) @comment
; Specific highlighting for common patterns
; Binary patterns (16-bit values)
(binary_value) @constant.numeric
; Decimal numbers
(decimal_value) @constant.numeric
; RAM references in headers
(register_name) @variable.builtin
; Common pin names
(pin_name) @property

View File

@@ -0,0 +1,9 @@
; Compare/Output file indentation rules
; No special indentation rules needed for compare/output files
; These files contain simple tabular data with consistent formatting
; All rows should be at the same indentation level
; Table rows should align consistently
; The pipe characters (|) provide natural alignment guides
; No nested structures require indentation changes

View File

@@ -0,0 +1,13 @@
; Compare/Output file outline queries
; Show header rows in the outline for navigation
(header_row
(header_cell (column_name) @name)) @item
(#set! item.kind "table")
; Show table structure - group data rows by sections
(table_row) @item
(#set! item.kind "row")
; No other special outline patterns needed for simple tabular data
; The header row provides the main navigation structure

View File

@@ -0,0 +1,6 @@
; Hack Assembly bracket matching
; Label declarations use parentheses
(label_declaration
"(" @open
")" @close) @container

View File

@@ -0,0 +1,7 @@
name = "Hack Assembly"
grammar = "hack_assembly"
scope = "source.hack_assembly"
path_suffixes = ["asm"]
line_comments = ["// "]
tab_size = 4
hard_tabs = false

View File

@@ -0,0 +1,103 @@
; Hack Assembly syntax highlighting queries based on actual node types
; A-instruction marker
"@" @punctuation.special
; A-instruction components
(a_instruction
(constant) @constant.numeric)
(a_instruction
(symbol
(predefined_symbol) @constant.builtin))
(a_instruction
(symbol
(user_symbol) @variable))
; C-instruction components
(dest) @type
(comp) @operator
(jump) @keyword.control
; Assignment and jump operators
"=" @operator
";" @punctuation.delimiter
; Label declarations
(label_declaration
"(" @punctuation.bracket
(symbol) @label
")" @punctuation.bracket)
; Comments
(comment) @comment
; Predefined symbols
"SP" @constant.builtin
"LCL" @constant.builtin
"ARG" @constant.builtin
"THIS" @constant.builtin
"THAT" @constant.builtin
"SCREEN" @constant.builtin
"KBD" @constant.builtin
; Virtual registers R0-R15 (handled by predefined_symbol pattern)
(predefined_symbol) @constant.builtin
; User-defined symbols
(user_symbol) @variable
; Constants
(constant) @constant.numeric
; Computation operations
"0" @constant.numeric
"1" @constant.numeric
"-1" @constant.numeric
; Register references
"D" @variable.builtin
"A" @variable.builtin
"M" @variable.builtin
; Arithmetic operations
"D+1" @operator
"A+1" @operator
"M+1" @operator
"D-1" @operator
"A-1" @operator
"M-1" @operator
"D+A" @operator
"D-A" @operator
"A-D" @operator
"D+M" @operator
"D-M" @operator
"M-D" @operator
; Logical operations
"!D" @operator
"!A" @operator
"!M" @operator
"-D" @operator
"-A" @operator
"-M" @operator
"D&A" @operator
"D|A" @operator
"D&M" @operator
"D|M" @operator
; Destination combinations
"MD" @type
"AM" @type
"AD" @type
"AMD" @type
; Jump conditions
"JGT" @keyword.control
"JEQ" @keyword.control
"JGE" @keyword.control
"JLT" @keyword.control
"JNE" @keyword.control
"JLE" @keyword.control
"JMP" @keyword.control

View File

@@ -0,0 +1,8 @@
; Hack Assembly indentation rules
; No special indentation rules needed for Hack Assembly
; since it's a flat assembly language with no nested structures
; All instructions should be at the same indentation level
; Labels can optionally be outdented or at the same level
; but we'll keep them at the same level for simplicity

View File

@@ -0,0 +1,21 @@
; Hack Assembly outline queries
; Show label declarations in the outline
(label_declaration
(symbol) @name) @item
; Show A-instructions with symbols as outline items
(a_instruction
(symbol) @name) @item
; Show A-instructions with constants as outline items
(a_instruction
(constant) @name) @item
; Show C-instructions with jumps as outline items (control flow)
(c_instruction
(jump) @name) @item
; Show comments that look like section headers
(comment) @item
(#match? @item "^//\\s*[A-Z].*|^//.*[Ss]ection|^//.*[Pp]art|^//.*[Ff]unction|^//.*[Ll]oop|^//.*[Ee]nd")

View File

@@ -0,0 +1,6 @@
; Bracket matching for Hack Binary
; No special brackets needed for binary files

View File

@@ -0,0 +1,11 @@
name = "Hack Binary"
grammar = "hack_binary"
scope = "source.hack_binary"
path_suffixes = ["hackbin"]
line_comments = ["// "]
tab_size = 4
hard_tabs = false

View File

@@ -0,0 +1,14 @@
; Hack Binary syntax highlighting queries
; 16-bit binary instructions
(bit_sequence) @constant.numeric
; Comments
(comment) @comment
; Binary digits highlighting
(bit_sequence) @constant.numeric

View File

@@ -0,0 +1,4 @@
; Hack Binary indentation rules
; Binary files typically don't need special indentation

View File

@@ -0,0 +1,4 @@
; Hack Binary outline rules
; Binary instructions don't have hierarchical structure

Some files were not shown because too many files have changed in this diff Show More