Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions crates/oxc/examples/compiler.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
#![expect(clippy::print_stdout)]
//! # Complete Compiler Example
//!
//! This example demonstrates the complete Oxc compilation pipeline including
//! parsing, semantic analysis, transformation, and code generation.
//!
//! ## Usage
//!
//! Create a `test.js` file and run:
//! ```bash
//! cargo run -p oxc --example compiler --features="full" [filename]
//! ```

use std::{env, io, path::Path};

Expand All @@ -10,12 +21,14 @@ use oxc::{Compiler, span::SourceType};
// * `cargo run -p oxc --example compiler --features="full"`
// * `just watch 'run -p oxc --example compiler --features="full"'`

/// Run the complete Oxc compilation pipeline on a JavaScript/TypeScript file
fn main() -> io::Result<()> {
let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
let path = Path::new(&name);
let source_text = std::fs::read_to_string(path)?;
let source_type = SourceType::from_path(path).unwrap();

// Execute the full compilation pipeline
match Compiler::default().execute(&source_text, source_type, path) {
Ok(printed) => {
println!("{printed}");
Expand Down
22 changes: 22 additions & 0 deletions crates/oxc_codegen/examples/codegen.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,21 @@
#![expect(clippy::print_stdout)]
//! # Code Generation Example
//!
//! This example demonstrates how to use the Oxc code generator to convert an AST
//! back into JavaScript code. It supports minification and idempotency testing.
//!
//! ## Usage
//!
//! Create a `test.js` file and run:
//! ```bash
//! cargo run -p oxc_codegen --example codegen [filename] [--minify] [--twice]
//! ```
//!
//! ## Options
//!
//! - `--minify`: Generate minified output
//! - `--twice`: Test idempotency by parsing and generating twice

use std::path::Path;

use oxc_allocator::Allocator;
Expand All @@ -13,6 +30,7 @@ use pico_args::Arguments;
// run `cargo run -p oxc_codegen --example codegen`
// or `cargo watch -x "run -p oxc_codegen --example codegen"`

/// Demonstrate code generation with optional minification and idempotency testing
fn main() -> std::io::Result<()> {
let mut args = Arguments::from_env();

Expand All @@ -25,13 +43,15 @@ fn main() -> std::io::Result<()> {
let source_type = SourceType::from_path(path).unwrap();
let mut allocator = Allocator::default();

// First round: parse and generate
let printed = {
let program = parse(&allocator, &source_text, source_type);
codegen(&program, minify)
};
println!("First time:");
println!("{printed}");

// Optional second round to test idempotency
if twice {
// Reset the allocator as we don't need the first AST any more
allocator.reset();
Expand All @@ -48,6 +68,7 @@ fn main() -> std::io::Result<()> {
Ok(())
}

/// Parse JavaScript/TypeScript source code into an AST
fn parse<'a>(
allocator: &'a Allocator,
source_text: &'a str,
Expand All @@ -65,6 +86,7 @@ fn parse<'a>(
ret.program
}

/// Generate JavaScript code from an AST
fn codegen(program: &Program<'_>, minify: bool) -> String {
Codegen::new()
.with_options(if minify { CodegenOptions::minify() } else { CodegenOptions::default() })
Expand Down
16 changes: 16 additions & 0 deletions crates/oxc_codegen/examples/sourcemap.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
#![expect(clippy::print_stdout)]
//! # Source Map Generation Example
//!
//! This example demonstrates how to generate source maps alongside JavaScript code.
//! It generates a visualization URL for inspecting the source map.
//!
//! ## Usage
//!
//! Create a `test.js` file and run:
//! ```bash
//! cargo run -p oxc_codegen --example sourcemap [filename]
//! ```

use std::{env, path::Path};

use base64::{Engine, prelude::BASE64_STANDARD};
Expand All @@ -11,6 +23,7 @@ use oxc_span::SourceType;
// 1. create a `test.js`
// 2. run `cargo run -p oxc_codegen --example sourcemap`

/// Generate source maps and provide a visualization URL
fn main() -> std::io::Result<()> {
let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
let path = Path::new(&name);
Expand All @@ -19,6 +32,7 @@ fn main() -> std::io::Result<()> {
let allocator = Allocator::default();
let ret = Parser::new(&allocator, &source_text, source_type).parse();

// Handle parsing errors
if !ret.errors.is_empty() {
for error in ret.errors {
let error = error.with_source_code(source_text.clone());
Expand All @@ -27,13 +41,15 @@ fn main() -> std::io::Result<()> {
return Ok(());
}

// Generate code with source map
let CodegenReturn { code, map, .. } = Codegen::new()
.with_options(CodegenOptions {
source_map_path: Some(path.to_path_buf()),
..CodegenOptions::default()
})
.build(&ret.program);

// Create visualization URL if source map was generated
if let Some(source_map) = map {
let result = source_map.to_json_string();
let hash =
Expand Down
16 changes: 16 additions & 0 deletions crates/oxc_formatter/examples/formatter.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
#![expect(clippy::print_stdout)]
//! # Formatter Example
//!
//! This example demonstrates how to use the Oxc formatter to format JavaScript and TypeScript code.
//!
//! ## Usage
//!
//! Create a `test.js` file and run:
//! ```bash
//! cargo run -p oxc_formatter --example formatter [filename]
//! ```

use std::{fs, path::Path};

Expand All @@ -8,14 +18,18 @@ use oxc_parser::{ParseOptions, Parser};
use oxc_span::SourceType;
use pico_args::Arguments;

/// Format a JavaScript or TypeScript file
fn main() -> Result<(), String> {
let mut args = Arguments::from_env();
let name = args.free_from_str().unwrap_or_else(|_| "test.js".to_string());

// Read source file
let path = Path::new(&name);
let source_text = fs::read_to_string(path).map_err(|_| format!("Missing '{name}'"))?;
let source_type = SourceType::from_path(path).unwrap();
let allocator = Allocator::new();

// Parse the source code
let ret = Parser::new(&allocator, &source_text, source_type)
.with_options(ParseOptions {
preserve_parens: false,
Expand All @@ -24,12 +38,14 @@ fn main() -> Result<(), String> {
})
.parse();

// Report any parsing errors
for error in ret.errors {
let error = error.with_source_code(source_text.clone());
println!("{error:?}");
println!("Parsed with Errors.");
}

// Format the parsed code
let options = FormatOptions::default();
let code = Formatter::new(&allocator, options).build(&ret.program);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
#![expect(clippy::print_stdout)]
//! # Isolated Declarations Example
//!
//! This example demonstrates how to generate TypeScript declaration files (.d.ts)
//! from TypeScript source code using isolated declarations.
//!
//! ## Usage
//!
//! Create a `test.ts` file and run:
//! ```bash
//! cargo run -p oxc_isolated_declarations --example isolated_declarations [filename]
//! ```

use std::{env, path::Path};

use oxc_allocator::Allocator;
Expand All @@ -12,6 +24,7 @@ use oxc_span::SourceType;
// run `cargo run -p oxc_isolated_declarations --example isolated_declarations`
// or `just example isolated_declarations`

/// Generate TypeScript declaration files from TypeScript source
fn main() -> std::io::Result<()> {
let name = env::args().nth(1).unwrap_or_else(|| "test.ts".to_string());
let path = Path::new(&name);
Expand Down
19 changes: 18 additions & 1 deletion crates/oxc_linter/examples/linter.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
#![expect(clippy::print_stdout)]
//! The simplest linter
//! # Simple Linter Example
//!
//! This example demonstrates how to create a basic linter using Oxc's parser and semantic analyzer.
//! It implements simple rules to detect debugger statements and empty destructuring patterns.
//!
//! ## Usage
//!
//! Create a `test.js` file and run:
//! ```bash
//! cargo run -p oxc_linter --example linter [filename]
//! ```

use std::{env, path::Path};

Expand All @@ -15,6 +25,7 @@ use oxc_span::{SourceType, Span};
// run `cargo run -p oxc_linter --example linter`
// or `cargo watch -x "run -p oxc_linter --example linter"`

/// Run a simple linter on a JavaScript file
fn main() -> std::io::Result<()> {
let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string());
let path = Path::new(&name);
Expand All @@ -29,10 +40,12 @@ fn main() -> std::io::Result<()> {
return Ok(());
}

// Build semantic model for AST analysis
let semantic_ret = SemanticBuilder::new().build(&ret.program);

let mut errors: Vec<OxcDiagnostic> = vec![];

// Check for linting violations
for node in semantic_ret.semantic.nodes() {
match node.kind() {
AstKind::DebuggerStatement(stmt) => {
Expand All @@ -48,6 +61,7 @@ fn main() -> std::io::Result<()> {
}
}

// Report results
if errors.is_empty() {
println!("Success!");
} else {
Expand All @@ -57,13 +71,15 @@ fn main() -> std::io::Result<()> {
Ok(())
}

/// Print diagnostic errors with source context
fn print_errors(source_text: &str, errors: Vec<OxcDiagnostic>) {
for error in errors {
let error = error.with_source_code(source_text.to_string());
println!("{error:?}");
}
}

/// Create a diagnostic for debugger statements
// This prints:
//
// ⚠ `debugger` statement is not allowed
Expand All @@ -75,6 +91,7 @@ fn no_debugger(debugger_span: Span) -> OxcDiagnostic {
OxcDiagnostic::error("`debugger` statement is not allowed").with_label(debugger_span)
}

/// Create a diagnostic for empty destructuring patterns
// This prints:
//
// ⚠ empty destructuring pattern is not allowed
Expand Down
17 changes: 17 additions & 0 deletions crates/oxc_minifier/examples/dce.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,21 @@
#![expect(clippy::print_stdout)]
//! # Dead Code Elimination Example
//!
//! This example demonstrates dead code elimination (DCE) using the Oxc compressor.
//! It removes unreachable code and unused variables.
//!
//! ## Usage
//!
//! Create a `test.js` file and run:
//! ```bash
//! cargo run -p oxc_minifier --example dce [filename] [--nospace] [--twice]
//! ```
//!
//! ## Options
//!
//! - `--nospace`: Remove extra whitespace
//! - `--twice`: Test idempotency by running twice

use std::path::Path;

use oxc_allocator::Allocator;
Expand Down
18 changes: 18 additions & 0 deletions crates/oxc_minifier/examples/mangler.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,22 @@
#![expect(clippy::print_stdout)]
//! # Variable Name Mangling Example
//!
//! This example demonstrates variable name mangling using the Oxc mangler.
//! It shortens variable names to reduce file size.
//!
//! ## Usage
//!
//! Create a `test.js` file and run:
//! ```bash
//! cargo run -p oxc_minifier --example mangler [filename] [options]
//! ```
//!
//! ## Options
//!
//! - `--keep-names`: Preserve function and class names
//! - `--debug`: Enable debug output
//! - `--twice`: Test idempotency by running twice

use std::path::Path;

use oxc_allocator::Allocator;
Expand Down
19 changes: 19 additions & 0 deletions crates/oxc_minifier/examples/minifier.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,23 @@
#![expect(clippy::print_stdout)]
//! # Minifier Example
//!
//! This example demonstrates the Oxc minifier with options for compression,
//! mangling, and source map generation.
//!
//! ## Usage
//!
//! Create a `test.js` file and run:
//! ```bash
//! cargo run -p oxc_minifier --example minifier [filename] [options]
//! ```
//!
//! ## Options
//!
//! - `--mangle`: Enable variable name mangling
//! - `--nospace`: Remove extra whitespace
//! - `--twice`: Test idempotency by running twice
//! - `--sourcemap`: Generate source maps

use std::path::{Path, PathBuf};

use base64::{Engine, prelude::BASE64_STANDARD};
Expand Down
Loading
Loading