phpast: output as json

This commit is contained in:
Ryan Chandler 2022-07-19 16:56:55 +01:00
parent 97c148e099
commit 8b143869a8
No known key found for this signature in database
GPG Key ID: F113BCADDB3B0CCA
4 changed files with 28 additions and 9 deletions

View File

@ -4,6 +4,8 @@ version = "0.1.0"
edition = "2021"
[dependencies]
serde = "1.0.139"
serde_json = "1.0.82"
structopt = { version = "0.3.26", features = ["color"] }
trunk_lexer = { path = "../trunk_lexer" }
trunk_parser = { path = "../trunk_parser" }

View File

@ -1,4 +1,5 @@
use std::{path::PathBuf, process::exit};
use serde_json::to_string;
use structopt::StructOpt;
use trunk_lexer::Lexer;
use trunk_parser::Parser;
@ -8,6 +9,9 @@ use trunk_parser::Parser;
struct Args {
#[structopt(parse(from_os_str), help = "The input file to use.")]
file: PathBuf,
#[structopt(short, long, help = "Output the abstract syntax tree as JSON.")]
json: bool,
}
fn main() {
@ -33,5 +37,15 @@ fn main() {
},
};
println!("{:#?}", ast);
if args.json {
match to_string(&ast) {
Ok(json) => println!("{}", json),
Err(e) => {
eprintln!("Failed to generate JSON, error: {}", e);
exit(1);
}
};
} else {
println!("{:#?}", ast);
}
}

View File

@ -6,7 +6,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = { version = "1.0.139", features = ["derive"] }
serde_json = "1.0.82"
trunk_lexer = { path = "../trunk_lexer" }
[lib]
doctest = false
doctest = false

View File

@ -1,9 +1,10 @@
use serde::Serialize;
use trunk_lexer::TokenKind;
pub type Block = Vec<Statement>;
pub type Program = Block;
#[derive(Debug, PartialEq, Clone)]
#[derive(Debug, PartialEq, Clone, Serialize)]
pub struct Identifier {
name: String,
}
@ -20,7 +21,7 @@ impl From<&String> for Identifier {
}
}
#[derive(Debug, PartialEq, Clone)]
#[derive(Debug, PartialEq, Clone, Serialize)]
pub struct Param {
name: Expression,
}
@ -43,7 +44,7 @@ impl From<&str> for Param {
}
}
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, Serialize)]
pub enum MethodFlag {
Public,
Protected,
@ -51,7 +52,7 @@ pub enum MethodFlag {
Static,
}
#[derive(Debug, PartialEq, Clone)]
#[derive(Debug, PartialEq, Clone, Serialize)]
pub enum Statement {
InlineHtml(String),
Var {
@ -92,7 +93,7 @@ pub enum Statement {
}
}
#[derive(Debug, PartialEq, Clone)]
#[derive(Debug, PartialEq, Clone, Serialize)]
pub enum Expression {
Int(i64),
Variable(String),
@ -103,13 +104,13 @@ pub enum Expression {
Array(Vec<ArrayItem>),
}
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ArrayItem {
pub key: Option<Expression>,
pub value: Expression,
}
#[derive(Debug, PartialEq, Clone)]
#[derive(Debug, PartialEq, Clone, Serialize)]
pub enum InfixOp {
Add,
Sub,