use crate::formatter::config::FormatConfig;
use crate::parser::ast::{
parse_source, Ast, AstNode, EnumDecl, EnumMember, FieldConstraintDecl, FieldDecl, FieldType,
FieldTypeRef, FileMetadata, ImportDecl, ImportItem, ImportSpecifier, OperationClause,
OperationDecl, PolicyBinding, RecordDecl,
};
use crate::policy::Expression;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::fmt;
#[derive(Debug)]
pub enum FormatError {
ParseError(String),
InternalError(String),
}
impl fmt::Display for FormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FormatError::ParseError(msg) => write!(f, "Parse error: {}", msg),
FormatError::InternalError(msg) => write!(f, "Internal error: {}", msg),
}
}
}
impl std::error::Error for FormatError {}
pub fn format(source: &str, config: FormatConfig) -> Result<String, FormatError> {
if config.preserve_comments {
format_preserving_comments(source, config)
} else {
format_without_comments(source, config)
}
}
fn format_without_comments(source: &str, config: FormatConfig) -> Result<String, FormatError> {
let ast = parse_source(source).map_err(|e| FormatError::ParseError(e.to_string()))?;
let mut formatter = Formatter::new(config, None);
formatter.format_ast(&ast);
Ok(formatter.output)
}
pub fn format_preserving_comments(
source: &str,
config: FormatConfig,
) -> Result<String, FormatError> {
use crate::formatter::comments::CommentedSource;
let commented = CommentedSource::new(source);
let ast = parse_source(source).map_err(|e| FormatError::ParseError(e.to_string()))?;
let mut formatter = Formatter::new(config, Some(commented));
formatter.format_ast(&ast);
Ok(formatter.output)
}
pub(crate) struct Formatter {
config: FormatConfig,
output: String,
indent_level: usize,
commented_source: Option<crate::formatter::comments::CommentedSource>,
}
impl Formatter {
fn new(
config: FormatConfig,
commented_source: Option<crate::formatter::comments::CommentedSource>,
) -> Self {
Self {
config,
output: String::new(),
indent_level: 0,
commented_source,
}
}
fn format_ast(&mut self, ast: &Ast) {
let header_comments: Vec<_> = self
.commented_source
.as_ref()
.map(|cs| cs.file_header_comments.clone())
.unwrap_or_default();
for comment in &header_comments {
self.write("// ");
self.write(&comment.text);
self.newline();
}
if !header_comments.is_empty() {
self.newline();
}
self.format_file_metadata(&ast.metadata);
let mut emitted_lines: std::collections::BTreeSet<usize> =
header_comments.iter().map(|c| c.line).collect();
let all_comments: Vec<crate::formatter::comments::Comment> = self
.commented_source
.as_ref()
.map(|cs| cs.comments.values().flatten().cloned().collect())
.unwrap_or_default();
let mut need_separator =
!ast.metadata.imports.is_empty() || ast.metadata.namespace.is_some();
for decl in ast.declarations.iter() {
let pending: Vec<_> = all_comments
.iter()
.filter(|c| c.line < decl.line && !emitted_lines.contains(&c.line))
.collect();
if !pending.is_empty() {
if need_separator {
self.newline();
}
for comment in &pending {
self.write("// ");
self.write(&comment.text);
self.newline();
emitted_lines.insert(comment.line);
}
} else if need_separator {
self.newline();
}
let start = self.output.len();
self.format_declaration(&decl.node);
let trailing: Vec<_> = all_comments
.iter()
.filter(|c| {
c.is_trailing && c.line == decl.line && !emitted_lines.contains(&c.line)
})
.collect();
for comment in trailing {
let eol = self.output[start..]
.find('\n')
.map(|p| start + p)
.unwrap_or(self.output.len());
self.output
.insert_str(eol, &format!(" // {}", comment.text));
emitted_lines.insert(comment.line);
}
need_separator = true;
}
let remaining: Vec<_> = all_comments
.iter()
.filter(|c| !emitted_lines.contains(&c.line))
.collect();
if !remaining.is_empty() {
if need_separator {
self.newline();
}
for comment in remaining {
self.write("// ");
self.write(&comment.text);
self.newline();
emitted_lines.insert(comment.line);
}
}
if self.config.trailing_newline && !self.output.ends_with('\n') {
self.output.push('\n');
}
}
fn format_file_metadata(&mut self, meta: &FileMetadata) {
if let Some(ref ns) = meta.namespace {
self.write("@namespace ");
self.write_string_literal(ns);
self.newline();
}
if let Some(ref version) = meta.version {
self.write("@version ");
self.write_string_literal(version);
self.newline();
}
if let Some(ref owner) = meta.owner {
self.write("@owner ");
self.write_string_literal(owner);
self.newline();
}
if let Some(ref profile) = meta.profile {
self.write("@profile ");
self.write_string_literal(profile);
self.newline();
}
if (meta.namespace.is_some()
|| meta.version.is_some()
|| meta.owner.is_some()
|| meta.profile.is_some())
&& !meta.imports.is_empty()
{
self.newline();
}
let mut imports = meta.imports.clone();
if self.config.sort_imports {
imports.sort_by(|a, b| a.from_module.cmp(&b.from_module));
}
for import in &imports {
self.format_import(import);
self.newline();
}
}
fn format_import(&mut self, import: &ImportDecl) {
self.write("import ");
match &import.specifier {
ImportSpecifier::Named(items) => {
self.write("{ ");
for (i, item) in items.iter().enumerate() {
if i > 0 {
self.write(", ");
}
self.format_import_item(item);
}
self.write(" }");
}
ImportSpecifier::Wildcard(alias) => {
self.write("* as ");
self.write(alias);
}
}
self.write(" from ");
self.write_string_literal(&import.from_module);
}
fn format_import_item(&mut self, item: &ImportItem) {
self.write(&item.name);
if let Some(ref alias) = item.alias {
self.write(" as ");
self.write(alias);
}
}
fn format_declaration(&mut self, node: &AstNode) {
match node {
AstNode::Export(inner) => {
self.write("export ");
self.format_declaration(&inner.node);
}
AstNode::Entity {
name,
version,
annotations,
domain,
body,
} => {
self.write("Entity ");
self.write_string_literal(name);
if let Some(v) = version {
self.write(" v");
self.write(v);
}
if let Some(replaces) = annotations.get("replaces") {
if let Some(s) = replaces.as_str() {
self.newline();
self.indent();
self.write_indent();
self.write("@replaces ");
if s.contains(" v") {
let parts: Vec<&str> = s.splitn(2, " v").collect();
self.write_string_literal(parts[0]);
if parts.len() > 1 {
self.write(" v");
self.write(parts[1]);
}
} else {
self.write_string_literal(s);
}
self.dedent();
}
}
if let Some(changes) = annotations.get("changes") {
if let Some(arr) = changes.as_array() {
self.newline();
self.indent();
self.write_indent();
self.write("@changes [");
for (i, change) in arr.iter().enumerate() {
if i > 0 {
self.write(", ");
}
if let Some(s) = change.as_str() {
self.write_string_literal(s);
}
}
self.write("]");
self.dedent();
}
}
if let Some(d) = domain {
self.write(" in ");
self.write(d);
}
if let Some(b) = body {
self.write(" {");
self.newline();
self.indent();
for field in &b.fields {
self.write_indent();
self.format_field_decl(field);
self.newline();
}
self.dedent();
self.write_indent();
self.write("}");
}
self.newline();
}
AstNode::Resource {
name,
annotations,
unit_name,
domain,
} => {
self.write("Resource ");
self.write_string_literal(name);
if let Some(replaces) = annotations.get("replaces") {
if let Some(s) = replaces.as_str() {
self.newline();
self.indent();
self.write_indent();
self.write("@replaces ");
if s.contains(" v") {
let parts: Vec<&str> = s.splitn(2, " v").collect();
self.write_string_literal(parts[0]);
if parts.len() > 1 {
self.write(" v");
self.write(parts[1]);
}
} else {
self.write_string_literal(s);
}
self.dedent();
}
}
if let Some(changes) = annotations.get("changes") {
if let Some(arr) = changes.as_array() {
self.newline();
self.indent();
self.write_indent();
self.write("@changes [");
for (i, change) in arr.iter().enumerate() {
if i > 0 {
self.write(", ");
}
if let Some(s) = change.as_str() {
self.write_string_literal(s);
}
}
self.write("]");
self.dedent();
}
}
if let Some(u) = unit_name {
self.write(" ");
self.write(u);
}
if let Some(d) = domain {
self.write(" in ");
self.write(d);
}
self.newline();
}
AstNode::Flow {
resource_name,
annotations,
from_entity,
to_entity,
quantity,
} => {
self.write("Flow ");
self.write_string_literal(resource_name);
if let Some(replaces) = annotations.get("replaces") {
if let Some(s) = replaces.as_str() {
self.newline();
self.indent();
self.write_indent();
self.write("@replaces ");
if s.contains(" v") {
let parts: Vec<&str> = s.splitn(2, " v").collect();
self.write_string_literal(parts[0]);
if parts.len() > 1 {
self.write(" v");
self.write(parts[1]);
}
} else {
self.write_string_literal(s);
}
self.dedent();
}
}
if let Some(changes) = annotations.get("changes") {
if let Some(arr) = changes.as_array() {
self.newline();
self.indent();
self.write_indent();
self.write("@changes [");
for (i, change) in arr.iter().enumerate() {
if i > 0 {
self.write(", ");
}
if let Some(s) = change.as_str() {
self.write_string_literal(s);
}
}
self.write("]");
self.dedent();
}
}
self.write(" from ");
self.write_string_literal(from_entity);
self.write(" to ");
self.write_string_literal(to_entity);
if let Some(q) = quantity {
self.write(" quantity ");
self.write(&q.to_string());
}
self.newline();
}
AstNode::Pattern { name, regex } => {
self.write("Pattern ");
self.write_string_literal(name);
self.write(" matches ");
self.write_string_literal(regex);
self.newline();
}
AstNode::Role { name, domain } => {
self.write("Role ");
self.write_string_literal(name);
if let Some(d) = domain {
self.write(" in ");
self.write(d);
}
self.newline();
}
AstNode::Relation {
name,
subject_role,
predicate,
object_role,
via_flow,
} => {
self.write("Relation ");
self.write_string_literal(name);
self.newline();
self.indent();
self.write_indent();
self.write("subject: ");
self.write_string_literal(subject_role);
self.newline();
self.write_indent();
self.write("predicate: ");
self.write_string_literal(predicate);
self.newline();
self.write_indent();
self.write("object: ");
self.write_string_literal(object_role);
if let Some(flow) = via_flow {
self.newline();
self.write_indent();
self.write("via: flow ");
self.write_string_literal(flow);
}
self.dedent();
self.newline();
}
AstNode::Dimension { name } => {
self.write("Dimension ");
self.write_string_literal(name);
self.newline();
}
AstNode::UnitDeclaration {
symbol,
dimension,
factor,
base_unit,
} => {
self.write("Unit ");
self.write_string_literal(symbol);
self.write(" of ");
self.write_string_literal(dimension);
self.write(" factor ");
self.write(&factor.to_string());
self.write(" base ");
self.write_string_literal(base_unit);
self.newline();
}
AstNode::Policy {
name,
version,
metadata,
expression,
} => {
self.write("Policy ");
self.write(name);
if let (Some(kind), Some(modality), Some(priority)) =
(&metadata.kind, &metadata.modality, metadata.priority)
{
self.write(" per ");
self.write(&format!("{}", kind));
self.write(" ");
self.write(&format!("{}", modality));
self.write(" priority ");
self.write(&priority.to_string());
}
if let Some(ref rationale) = metadata.rationale {
self.newline();
self.indent();
self.write_indent();
self.write("@rationale ");
self.write_string_literal(rationale);
self.dedent();
}
if !metadata.tags.is_empty() {
self.newline();
self.indent();
self.write_indent();
self.write("@tags [");
for (i, tag) in metadata.tags.iter().enumerate() {
if i > 0 {
self.write(", ");
}
self.write_string_literal(tag);
}
self.write("]");
self.dedent();
}
if let Some(v) = version {
self.newline();
self.indent();
self.write_indent();
self.write("v");
self.write(v);
self.dedent();
}
self.newline();
self.indent();
self.write_indent();
self.write("as: ");
self.format_expression(expression);
self.dedent();
self.newline();
}
AstNode::Instance {
name,
entity_type,
fields,
} => {
self.write("Instance ");
self.write(name);
self.write(" of ");
self.write_string_literal(entity_type);
if !fields.is_empty() {
self.write(" {");
self.newline();
self.indent();
let mut sorted_fields: Vec<_> = fields.iter().collect();
sorted_fields.sort_by_key(|(k, _)| *k);
for (i, (field_name, expr)) in sorted_fields.iter().enumerate() {
self.write_indent();
self.write(field_name);
self.write(": ");
self.format_expression(expr);
if i < sorted_fields.len() - 1 {
self.write(",");
}
self.newline();
}
self.dedent();
self.write_indent();
self.write("}");
}
self.newline();
}
AstNode::ConceptChange {
name,
from_version,
to_version,
migration_policy,
breaking_change,
} => {
self.write("ConceptChange ");
self.write_string_literal(name);
self.newline();
self.indent();
self.write_indent();
self.write("@from_version v");
self.write(from_version);
self.newline();
self.write_indent();
self.write("@to_version v");
self.write(to_version);
self.newline();
self.write_indent();
self.write("@migration_policy ");
self.write(migration_policy);
self.newline();
self.write_indent();
self.write("@breaking_change ");
self.write(if *breaking_change { "true" } else { "false" });
self.dedent();
self.newline();
}
AstNode::Metric {
name,
expression,
metadata,
} => {
self.write("Metric ");
self.write_string_literal(name);
self.write(" as:");
self.newline();
self.indent();
self.write_indent();
self.format_expression(expression);
if let Some(ref interval) = metadata.refresh_interval {
self.newline();
self.write_indent();
self.write("@refresh_interval ");
self.write(&interval.num_seconds().to_string());
self.write(" \"seconds\"");
}
if let Some(ref unit) = metadata.unit {
self.newline();
self.write_indent();
self.write("@unit ");
self.write_string_literal(unit);
}
if let Some(threshold) = &metadata.threshold {
self.newline();
self.write_indent();
self.write("@threshold ");
self.write(&threshold.to_string());
}
if let Some(ref severity) = metadata.severity {
self.newline();
self.write_indent();
self.write("@severity ");
self.write_string_literal(&format!("{:?}", severity).to_lowercase());
}
if let Some(target) = &metadata.target {
self.newline();
self.write_indent();
self.write("@target ");
self.write(&target.to_string());
}
if let Some(ref window) = metadata.window {
self.newline();
self.write_indent();
self.write("@window ");
self.write(&window.num_seconds().to_string());
self.write(" \"seconds\"");
}
self.dedent();
self.newline();
}
AstNode::MappingDecl {
name,
target,
rules,
} => {
self.write("Mapping ");
self.write_string_literal(name);
self.write(" for ");
self.write(&format!("{}", target).to_lowercase());
self.write(" {");
self.newline();
self.indent();
for rule in rules {
self.write_indent();
self.write(&rule.primitive_type);
self.write(" ");
self.write_string_literal(&rule.primitive_name);
self.write(" -> ");
self.write(&rule.target_type);
self.write(" { ");
let mut first = true;
for (k, v) in &rule.fields {
if !first {
self.write(", ");
}
self.write(k);
self.write(": ");
self.write(&v.to_string());
first = false;
}
self.write(" }");
self.newline();
}
self.dedent();
self.write_indent();
self.write("}");
self.newline();
}
AstNode::ProjectionDecl {
name,
target,
overrides,
} => {
self.write("Projection ");
self.write_string_literal(name);
self.write(" for ");
self.write(&format!("{}", target).to_lowercase());
self.write(" {");
self.newline();
self.indent();
for over in overrides {
self.write_indent();
self.write(&over.primitive_type);
self.write(" ");
self.write_string_literal(&over.primitive_name);
self.write(" { ");
let mut first = true;
for (k, v) in &over.fields {
if !first {
self.write(", ");
}
self.write(k);
self.write(": ");
self.write(&v.to_string());
first = false;
}
self.write(" }");
self.newline();
}
self.dedent();
self.write_indent();
self.write("}");
self.newline();
}
AstNode::Cell { name, annotations } => {
self.format_generic_decl("Cell", name, None, None, annotations)
}
AstNode::SystemDependency {
name,
version,
annotations,
} => self.format_generic_decl(
"SystemDependency",
name,
version.as_deref(),
None,
annotations,
),
AstNode::Runtime {
name,
version,
annotations,
} => self.format_generic_decl("Runtime", name, Some(version), None, annotations),
AstNode::Tool {
name,
version,
annotations,
} => self.format_generic_decl("Tool", name, Some(version), None, annotations),
AstNode::DependencySet { name, annotations } => {
self.format_generic_decl("DependencySet", name, None, None, annotations)
}
AstNode::Service {
name,
version,
annotations,
} => self.format_generic_decl("Service", name, version.as_deref(), None, annotations),
AstNode::Mount { name, annotations } => {
self.format_generic_decl("Mount", name, None, None, annotations)
}
AstNode::Endpoint { name, annotations } => {
self.format_generic_decl("Endpoint", name, None, None, annotations)
}
AstNode::NetworkFlow {
name,
from_ref,
to_ref,
annotations,
} => self.format_generic_decl(
"NetworkFlow",
name,
None,
Some((from_ref.as_str(), to_ref.as_str())),
annotations,
),
AstNode::Credential { name, annotations } => {
self.format_generic_decl("Credential", name, None, None, annotations)
}
AstNode::RoleBinding { role, entity } => {
self.write("role_binding ");
self.write_string_literal(role);
self.write(" for ");
self.write_string_literal(entity);
self.newline();
}
AstNode::Record(r) => {
self.format_record(r);
self.newline();
}
AstNode::Enum(e) => {
self.format_enum(e);
self.newline();
}
AstNode::Operation(o) => {
self.format_operation(o);
self.newline();
}
}
}
pub(crate) fn node_to_string(node: &AstNode, indent_level: usize) -> String {
let mut f = Formatter::new(FormatConfig::default(), None);
f.indent_level = indent_level;
match node {
AstNode::Record(r) => f.format_record(r),
AstNode::Enum(e) => f.format_enum(e),
AstNode::Operation(o) => f.format_operation(o),
other => f.format_declaration(other),
}
f.output.trim_end().to_string()
}
fn format_field_decl(&mut self, field: &FieldDecl) {
if field.is_key {
self.write("key ");
}
self.write(&field.name);
self.write(": ");
self.format_field_type(&field.field_type);
if field.is_optional {
self.write(" optional");
}
if !field.constraints.is_empty() {
self.write(" (");
for (i, c) in field.constraints.iter().enumerate() {
if i > 0 {
self.write(", ");
}
self.format_field_constraint(c);
}
self.write(")");
}
if let Some(default) = &field.default {
self.write(" default ");
self.format_expression_default(default);
}
}
fn format_field_type(&mut self, ty: &FieldType) {
match ty {
FieldType::Scalar(s) => self.write(&s.symbol),
FieldType::Quantity(s) => self.format_param_type("quantity", s),
FieldType::Ref(s) => self.format_param_type("ref", s),
FieldType::Named(s) => self.format_field_type_ref(s),
FieldType::List(elem) => {
self.write("list<");
self.format_field_type(elem);
self.write(">");
}
}
}
fn format_param_type(&mut self, kw: &str, s: &FieldTypeRef) {
self.write(kw);
self.write("<");
self.format_field_type_ref(s);
self.write(">");
}
fn format_field_type_ref(&mut self, s: &FieldTypeRef) {
if let Some(alias) = &s.alias {
self.write(alias);
self.write(".");
}
self.write(&s.symbol);
}
fn format_field_constraint(&mut self, c: &FieldConstraintDecl) {
match c {
FieldConstraintDecl::MinLength(v) => {
self.write("min_length ");
self.write(&v.to_string());
}
FieldConstraintDecl::MaxLength(v) => {
self.write("max_length ");
self.write(&v.to_string());
}
FieldConstraintDecl::MinItems(v) => {
self.write("min_items ");
self.write(&v.to_string());
}
FieldConstraintDecl::MaxItems(v) => {
self.write("max_items ");
self.write(&v.to_string());
}
FieldConstraintDecl::ExclusiveMin(v) => {
self.write("exclusive_min ");
self.write(&v.to_string());
}
FieldConstraintDecl::ExclusiveMax(v) => {
self.write("exclusive_max ");
self.write(&v.to_string());
}
FieldConstraintDecl::Min(v) => {
self.write("min ");
self.write(&v.to_string());
}
FieldConstraintDecl::Max(v) => {
self.write("max ");
self.write(&v.to_string());
}
FieldConstraintDecl::Pattern(s) => {
self.write("pattern ");
self.write(s);
}
}
}
fn format_expression_default(&mut self, expr: &Expression) {
match expr {
Expression::Literal(v) => match v {
JsonValue::String(s) => self.write_string_literal(s),
other => self.write(&other.to_string()),
},
Expression::QuantityLiteral { value, unit } => {
self.write(&value.to_string());
self.write(" ");
self.write_string_literal(unit);
}
other => self.write(&other.to_string()),
}
}
fn format_record(&mut self, r: &RecordDecl) {
self.write("record ");
self.write(&r.name);
self.write(" {");
self.newline();
self.indent();
for field in &r.fields {
self.write_indent();
self.format_field_decl(field);
self.newline();
}
self.dedent();
self.write_indent();
self.write("}");
}
fn format_enum(&mut self, e: &EnumDecl) {
self.write("enum ");
self.write(&e.name);
self.write(" {");
self.newline();
self.indent();
for (i, m) in e.members.iter().enumerate() {
self.write_indent();
self.format_enum_member(m);
if i + 1 < e.members.len() {
self.write(",");
}
self.newline();
}
self.dedent();
self.write_indent();
self.write("}");
}
fn format_enum_member(&mut self, m: &EnumMember) {
self.write(&m.name);
self.write(" = ");
self.write_string_literal(&m.wire);
}
fn format_operation(&mut self, o: &OperationDecl) {
self.write("operation ");
self.write(&o.name);
self.write(" {");
self.newline();
self.indent();
let order = canonical_clause_order(&o.clauses);
for c in order {
self.write_indent();
self.format_operation_clause(c);
self.newline();
}
self.dedent();
self.write_indent();
self.write("}");
}
fn format_operation_clause(&mut self, clause: &OperationClause) {
match clause {
OperationClause::Intent(text) => {
self.write("intent ");
self.write_string_literal(text);
}
OperationClause::Direction { kind } => {
self.write("direction ");
self.write(kind);
}
OperationClause::Actor { actor } => {
self.write("actor ");
self.write(actor);
}
OperationClause::AccessPublic => {
self.write("access public");
}
OperationClause::AccessPolicyGoverned { bindings } => {
self.write("access policy_governed by ");
for (i, b) in bindings.iter().enumerate() {
if i > 0 {
self.write(", ");
}
self.format_policy_binding(b);
}
}
OperationClause::Input { reference } => {
self.write("input ");
self.write(reference);
}
OperationClause::Output { reference } => {
self.write("output ");
self.write(reference);
}
OperationClause::State { reference } => {
self.write("state ");
self.write(reference);
}
OperationClause::Effect { kind, reference } => {
self.write("effect ");
self.write(kind);
self.write(" ");
self.write(reference);
}
OperationClause::Transaction { kind } => {
self.write("transaction ");
self.write(kind);
}
OperationClause::Failure {
code,
kinds,
message,
} => {
self.write("failure ");
self.write(code);
self.write(" for ");
for (i, k) in kinds.iter().enumerate() {
if i > 0 {
self.write(", ");
}
self.write(k);
}
self.write(" ");
self.write_string_literal(message);
}
OperationClause::IdempotencyKeyed { field } => {
self.write("idempotency keyed_by ");
self.write(field);
}
OperationClause::IdempotencyInherent => {
self.write("idempotency inherent");
}
OperationClause::IdempotencyNotApplicable {
reason,
explanation,
} => {
self.write("idempotency not_applicable(");
self.write(reason);
self.write(", ");
self.write_string_literal(explanation);
self.write(")");
}
OperationClause::ConcurrencyUnique { field } => {
self.write("concurrency unique_key ");
self.write(field);
}
OperationClause::ConcurrencyOptimistic { field } => {
self.write("concurrency optimistic_version ");
self.write(field);
}
OperationClause::ConcurrencyReadSnapshot => {
self.write("concurrency read_snapshot");
}
OperationClause::EvidenceOperationTrace => {
self.write("evidence operation_trace");
}
OperationClause::LifecycleSynchronousRequestResponse => {
self.write("lifecycle synchronous_request_response");
}
}
}
fn format_policy_binding(&mut self, b: &PolicyBinding) {
self.write(&b.policy);
self.write(" at ");
self.write(&b.enforcement_point);
self.write(" fails with ");
self.write(&b.failure_code);
}
fn format_expression(&mut self, expr: &Expression) {
self.write(&format!("{}", expr));
}
fn format_generic_decl(
&mut self,
keyword: &str,
name: &str,
version: Option<&str>,
from_to: Option<(&str, &str)>,
annotations: &HashMap<String, JsonValue>,
) {
self.write(keyword);
self.write(" ");
self.write_string_literal(name);
if let Some(v) = version {
self.write(" version ");
self.write_string_literal(v);
}
if let Some((from, to)) = from_to {
self.write(" from ");
self.write_string_literal(from);
self.write(" to ");
self.write_string_literal(to);
}
let mut keys: Vec<_> = annotations.keys().collect();
keys.sort();
for key in keys {
self.newline();
self.indent();
self.write_indent();
self.write("@");
self.write(key);
self.write(" ");
self.write(&annotations[key].to_string());
self.dedent();
}
self.newline();
}
fn write(&mut self, s: &str) {
self.output.push_str(s);
}
fn write_string_literal(&mut self, s: &str) {
self.output.push('"');
for c in s.chars() {
match c {
'"' => self.output.push_str("\\\""),
'\\' => self.output.push_str("\\\\"),
'\n' => self.output.push_str("\\n"),
'\r' => self.output.push_str("\\r"),
'\t' => self.output.push_str("\\t"),
_ => self.output.push(c),
}
}
self.output.push('"');
}
fn newline(&mut self) {
self.output.push('\n');
}
fn write_indent(&mut self) {
let indent = self.config.indent_string();
for _ in 0..self.indent_level {
self.output.push_str(&indent);
}
}
fn indent(&mut self) {
self.indent_level += 1;
}
fn dedent(&mut self) {
if self.indent_level > 0 {
self.indent_level -= 1;
}
}
}
fn canonical_clause_order(clauses: &[OperationClause]) -> Vec<&OperationClause> {
use OperationClause::*;
let has = |k: &OperationClauseKind| clauses.iter().any(|c| clause_kind(c) == *k);
let complete = [
OperationClauseKind::Intent,
OperationClauseKind::Direction,
OperationClauseKind::Actor,
OperationClauseKind::Access,
OperationClauseKind::Input,
OperationClauseKind::Output,
OperationClauseKind::State,
OperationClauseKind::Effect,
OperationClauseKind::Transaction,
OperationClauseKind::Idempotency,
OperationClauseKind::Concurrency,
OperationClauseKind::Evidence,
OperationClauseKind::Lifecycle,
]
.iter()
.all(has)
&& clauses.iter().any(|c| matches!(c, Failure { .. }));
if !complete {
return clauses.iter().collect();
}
let mut ordered: Vec<&OperationClause> = Vec::with_capacity(clauses.len());
let kinds = [
OperationClauseKind::Intent,
OperationClauseKind::Direction,
OperationClauseKind::Actor,
OperationClauseKind::Access,
OperationClauseKind::Input,
OperationClauseKind::Output,
OperationClauseKind::State,
OperationClauseKind::Effect,
OperationClauseKind::Transaction,
];
for k in kinds {
if let Some(c) = clauses.iter().find(|c| clause_kind(c) == k) {
ordered.push(c);
}
}
for c in clauses.iter().filter(|c| matches!(c, Failure { .. })) {
ordered.push(c);
}
for k in [
OperationClauseKind::Idempotency,
OperationClauseKind::Concurrency,
OperationClauseKind::Evidence,
OperationClauseKind::Lifecycle,
] {
if let Some(c) = clauses.iter().find(|c| clause_kind(c) == k) {
ordered.push(c);
}
}
ordered
}
#[derive(PartialEq, Eq, Clone, Copy)]
enum OperationClauseKind {
Intent,
Direction,
Actor,
Access,
Input,
Output,
State,
Effect,
Transaction,
Failure,
Idempotency,
Concurrency,
Evidence,
Lifecycle,
}
fn clause_kind(c: &OperationClause) -> OperationClauseKind {
use OperationClause::*;
match c {
Intent { .. } => OperationClauseKind::Intent,
Direction { .. } => OperationClauseKind::Direction,
Actor { .. } => OperationClauseKind::Actor,
AccessPublic | AccessPolicyGoverned { .. } => OperationClauseKind::Access,
Input { .. } => OperationClauseKind::Input,
Output { .. } => OperationClauseKind::Output,
State { .. } => OperationClauseKind::State,
Effect { .. } => OperationClauseKind::Effect,
Transaction { .. } => OperationClauseKind::Transaction,
Failure { .. } => OperationClauseKind::Failure,
IdempotencyKeyed { .. } | IdempotencyInherent | IdempotencyNotApplicable { .. } => {
OperationClauseKind::Idempotency
}
ConcurrencyUnique { .. } | ConcurrencyOptimistic { .. } | ConcurrencyReadSnapshot => {
OperationClauseKind::Concurrency
}
EvidenceOperationTrace => OperationClauseKind::Evidence,
LifecycleSynchronousRequestResponse => OperationClauseKind::Lifecycle,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_entity_basic() {
let input = r#"Entity "Foo""#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("Entity \"Foo\""));
assert!(result.ends_with('\n'));
}
#[test]
fn test_format_entity_with_domain() {
let input = r#"Entity "Bar" in test"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("Entity \"Bar\" in test"));
}
#[test]
fn test_format_resource() {
let input = r#"Resource "Money" USD in finance"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("Resource \"Money\" USD in finance"));
}
#[test]
fn test_format_flow() {
let input = r#"Flow "Money" from "A" to "B" quantity 100"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("Flow \"Money\" from \"A\" to \"B\" quantity 100"));
}
#[test]
fn test_format_idempotent() {
let input = r#"Entity "Test" in foo"#;
let once = format(input, FormatConfig::default()).unwrap();
let twice = format(&once, FormatConfig::default()).unwrap();
assert_eq!(once, twice, "Formatting should be idempotent");
}
#[test]
fn test_format_multiple_declarations() {
let input = r#"
Entity "A"
Entity "B"
Resource "R" units
"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("Entity \"A\""));
assert!(result.contains("Entity \"B\""));
assert!(result.contains("Resource \"R\""));
}
#[test]
fn test_format_with_tabs() {
let input = r#"
Relation "Test"
subject: "A"
predicate: "rel"
object: "B"
"#;
let config = FormatConfig::default().with_tabs();
let result = format(input, config).unwrap();
assert!(result.contains('\t'), "Should use tabs for indentation");
}
#[test]
fn test_format_imports_sorted() {
let input = r#"
import { B } from "z.sea"
import { A } from "a.sea"
Entity "Test"
"#;
let config = FormatConfig::default();
let result = format(input, config).unwrap();
let a_pos = result.find("a.sea").unwrap();
let z_pos = result.find("z.sea").unwrap();
assert!(a_pos < z_pos, "Imports should be sorted alphabetically");
}
#[test]
fn test_format_policy_with_expression() {
let input = r#"Policy test as: x = 5"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("Policy test"));
assert!(result.contains("as:"));
assert!(!result.contains("Binary {"), "Should not use Debug format");
}
#[test]
fn test_format_instance_with_fields() {
let input = r#"
Instance test_user of "User" {
name: "Alice",
age: 30
}
"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("Instance test_user of \"User\""));
assert!(result.contains("name:"));
assert!(result.contains("age:"));
}
#[test]
fn test_format_preserves_header_comments() {
let input = r#"// This is a header comment
// Second line
Entity "Foo"
"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("// This is a header comment"));
assert!(result.contains("// Second line"));
assert!(result.contains("Entity \"Foo\""));
}
#[test]
fn test_format_without_comments() {
let input = r#"// Comment
Entity "Foo"
"#;
let config = FormatConfig {
preserve_comments: false,
..Default::default()
};
let result = format(input, config).unwrap();
assert!(!result.contains("// Comment"));
assert!(result.contains("Entity \"Foo\""));
}
fn quantifier_source(keyword: &str) -> String {
format!(
r#"Entity "A"
Entity "B"
Resource "R" units
Flow "R" from "A" to "B" quantity 1
Policy p as:
{keyword} f in flows: (f.quantity > 0)
"#
)
}
#[test]
fn test_format_quantifier_forall_round_trip() {
let input = quantifier_source("forall");
let once = format(&input, FormatConfig::default()).unwrap();
assert!(
parse_source(&once).is_ok(),
"formatted forall output must reparse: {once}"
);
let twice = format(&once, FormatConfig::default()).unwrap();
assert_eq!(once, twice, "fmt(fmt(x)) must equal fmt(x)");
}
#[test]
fn test_format_quantifier_exists_round_trip() {
let input = quantifier_source("exists");
let once = format(&input, FormatConfig::default()).unwrap();
assert!(
parse_source(&once).is_ok(),
"formatted exists output must reparse: {once}"
);
let twice = format(&once, FormatConfig::default()).unwrap();
assert_eq!(once, twice, "fmt(fmt(x)) must equal fmt(x)");
}
#[test]
fn test_format_quantifier_exists_unique_round_trip() {
let input = quantifier_source("exists_unique");
let once = format(&input, FormatConfig::default()).unwrap();
assert!(
parse_source(&once).is_ok(),
"formatted exists_unique output must reparse: {once}"
);
let twice = format(&once, FormatConfig::default()).unwrap();
assert_eq!(once, twice, "fmt(fmt(x)) must equal fmt(x)");
}
#[test]
fn test_format_quantifier_non_binary_condition_round_trip() {
let input = r#"Entity "A"
Entity "B"
Resource "R" units
Flow "R" from "A" to "B" quantity 1
Policy p as:
forall f in flows: (true)
"#;
let once = format(input, FormatConfig::default()).unwrap();
assert!(
!once.contains("(("),
"must not double-parenthesize a non-Binary condition: {once}"
);
assert!(
parse_source(&once).is_ok(),
"formatted output must reparse: {once}"
);
let twice = format(&once, FormatConfig::default()).unwrap();
assert_eq!(once, twice, "fmt(fmt(x)) must equal fmt(x)");
}
#[test]
fn test_format_quantifier_entity_instances_of_round_trip() {
let input = r#"Entity "A"
Instance a1 of "A" {
x: 5
}
Policy p as:
forall e in entity_instances of "A": (e.x > 0)
"#;
let once = format(input, FormatConfig::default()).unwrap();
assert!(
once.contains("entity_instances of \"A\""),
"must decode entity_instances:A back to SEA syntax: {once}"
);
assert!(
parse_source(&once).is_ok(),
"formatted output must reparse: {once}"
);
let twice = format(&once, FormatConfig::default()).unwrap();
assert_eq!(once, twice, "fmt(fmt(x)) must equal fmt(x)");
}
fn count_comment_lines(s: &str) -> usize {
s.lines()
.filter(|l| l.trim_start().starts_with("//"))
.count()
}
#[test]
fn test_format_comments_between_declarations() {
let input = r#"Entity "A"
// comment between declarations
Entity "B"
"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("// comment between declarations"));
assert!(parse_source(&result).is_ok(), "must reparse: {result}");
let twice = format(&result, FormatConfig::default()).unwrap();
assert_eq!(result, twice, "fmt(fmt(x)) must equal fmt(x)");
}
#[test]
fn test_format_comments_after_namespace_before_first_decl() {
let input = r#"@namespace "test"
// comment after namespace, before first declaration
Entity "A"
"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("// comment after namespace, before first declaration"));
assert!(parse_source(&result).is_ok(), "must reparse: {result}");
let twice = format(&result, FormatConfig::default()).unwrap();
assert_eq!(result, twice, "fmt(fmt(x)) must equal fmt(x)");
}
#[test]
fn test_format_comments_trailing_on_declaration() {
let input = r#"Entity "A" // trailing comment
Entity "B"
"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("// trailing comment"));
let lines: Vec<&str> = result.lines().collect();
let entity_a_line = lines
.iter()
.find(|l| l.contains("Entity \"A\""))
.expect("Entity A line not found");
assert!(
entity_a_line.contains("// trailing comment"),
"trailing comment should be on Entity A's line: {entity_a_line}"
);
assert!(parse_source(&result).is_ok(), "must reparse: {result}");
let twice = format(&result, FormatConfig::default()).unwrap();
assert_eq!(result, twice, "fmt(fmt(x)) must equal fmt(x)");
}
#[test]
fn test_format_comments_at_end_of_file() {
let input = r#"Entity "A"
Entity "B"
// trailing end-of-file comment
"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(result.contains("// trailing end-of-file comment"));
assert!(parse_source(&result).is_ok(), "must reparse: {result}");
let twice = format(&result, FormatConfig::default()).unwrap();
assert_eq!(result, twice, "fmt(fmt(x)) must equal fmt(x)");
}
#[test]
fn test_format_comments_string_literal_not_treated_as_comment() {
let input = r#"Entity "A"
Entity "B"
Resource "R" units
Flow "R" from "A" to "B" quantity 1
Policy p as:
f.resource CONTAINS "see https://example.com for details"
"#;
let result = format(input, FormatConfig::default()).unwrap();
assert!(
result.contains("https://example.com"),
"string literal content must survive: {result}"
);
assert_eq!(
count_comment_lines(input),
0,
"test fixture has no real comments"
);
assert_eq!(
count_comment_lines(&result),
0,
"must not manufacture a comment from a string literal: {result}"
);
assert!(parse_source(&result).is_ok(), "must reparse: {result}");
let twice = format(&result, FormatConfig::default()).unwrap();
assert_eq!(result, twice, "fmt(fmt(x)) must equal fmt(x)");
}
#[test]
fn test_format_comments_all_preserved_exactly_once() {
let input = r#"// header comment
@namespace "test"
// after namespace, before first decl
Entity "A" // trailing on entity
// between declarations
Entity "B"
// end of file comment
"#;
let result = format(input, FormatConfig::default()).unwrap();
for text in [
"// header comment",
"// after namespace, before first decl",
"// trailing on entity",
"// between declarations",
"// end of file comment",
] {
assert_eq!(
result.matches(text).count(),
1,
"expected exactly one occurrence of {text:?} in: {result}"
);
}
assert!(parse_source(&result).is_ok(), "must reparse: {result}");
let twice = format(&result, FormatConfig::default()).unwrap();
assert_eq!(result, twice, "fmt(fmt(x)) must equal fmt(x)");
}
}