Project

postscript

0.0
The project is in a healthy, maintained state
Postscript is a pure-Ruby PostScript (PS) / EPS parser, typed domain model, and serializer. It is the lower layer of the postsvg converter and is independently reusable for any tool that needs to read, write, or transform PostScript source.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Runtime

>= 0
 Project Readme

Postscript

Pure-Ruby PostScript (PS) / EPS parser, typed domain model, and serializer. The lower layer of the postsvg converter. Independently reusable for any tool that needs to read, write, or transform PostScript source.

Installation

gem install postscript

Usage

require "postscript"

# Parse PS source into a typed AST
program = Postscript::Source.parse(<<~PS)
  %!PS-Adobe-3.0 EPSF-3.0
  %%BoundingBox: 0 0 100 100
  newpath
  10 10 moveto
  90 10 lineto
  90 90 lineto
  10 90 lineto
  closepath
  fill
  showpage
PS

# Walk the AST
program.body.each do |node|
  puts node.class
end

# Re-serialize back to PS source
ps_text = Postscript::Serializer.call(program)
puts ps_text

Native engine (optional)

engine: :native tokenizes with the PostScript PARG grammar in grammars/ on the parsanol native engine:

program = Postscript.parse(source, engine: :native)
Postscript::Source::NativeEngine.available? # => true when it can run

It needs the parsanol gem (1.3.96 or newer, Ruby 3.2 or newer), which this gem does not depend on: add it to your Gemfile to use it. Without it, engine: :native raises Postscript::NativeEngineUnavailable.

It produces the same tokens, programs and errors as the default Ruby lexer; where the grammar rejects the source, the Ruby lexer tokenizes it. It is currently slower than the Ruby lexer, so the default is engine: :ruby. benchmark/parse.rb --engine native measures both.

Language levels

One grammar parses every language level; levels are vocabulary data, not grammar. An operator’s level comes from the PostScript Language Guide’s operator pages, plus data/operator_overrides.yml for what the Guide lacks. See the full inventory in docs/operators.adoc.

program = Postscript.parse("0 0 moveto shfill")
Postscript.level_violations(program, level: 2)
# => [#<struct Postscript::LevelViolation keyword="shfill", level=3>]

Without level:, the program’s %%LanguageLevel header is used. With no header, or one outside 1..3, the level is 3. An explicit level: must be 1, 2 or 3, or it raises ArgumentError. With a valid level, it reports violations and never raises for a parsed program.

Names with no vocabulary entry and calls to user procedures are never violations.

Known limitation: operators inside << >> dictionaries, and operators inside [ ] that the AST builder drops, are not checked.

Validation

Postscript.validate returns a LensCore::Report using the LensCore diagnostics v1 contract. Validation requires lens_core and Ruby >= 3.1; add the dependency to your Gemfile (currently pinned to commit 98c21c82bc97e3c8c4038048acdcec4a177c5f7c of lens_core). It loads lazily, so parsing and serialization remain usable without it. If it cannot load, validation raises Postscript::Error with the dependency requirements.

report = Postscript.validate("0 0 moveto shfill", level: 1)
report.valid # => false
report.summary # => { "errors" => 1, "warnings" => 0, "infos" => 0 }
diagnostic = report.diagnostics.first
diagnostic.requirement_id # => "postscript.level.operator-available"
diagnostic.message # => "shfill is Level 3; this program targets Level 1"
diagnostic.context
# => { "keyword" => "shfill", "required_level" => 3, "target_level" => 1 }
diagnostic.remediation # => "declare %%LanguageLevel: 3 or remove shfill"

Grammar errors stop validation before model checks. Level findings cite the operator’s vocabulary source and use the same explicit-level, header and default rules as Postscript.level_violations. For invalid grammar, the profile uses the explicit level or defaults to Level 3. Unknown names produce warnings; warnings alone do not make valid false. This static check recognizes def bindings but does not simulate execution or dictionary scope, and shares the model limitations described above.

The default engine: :auto uses the native engine when available and Ruby otherwise. Pass engine: :ruby to select Ruby, or engine: :native to require native support (Postscript::NativeEngineUnavailable is raised if unavailable). The defaults of parse and tokenize remain :ruby.

Grammar findings retain each engine’s message and put line, column, offset, rule, expected and engine in context. Coordinates are passed through from the engine. Diagnostics never have a location: LensCore v1 has no text location type. Model findings have no engine field, so accepted programs give identical reports across engines. Requirement IDs identify rules, with operator names kept in context. Diagnostic text is decoded as UTF-8; invalid byte sequences are displayed with the replacement character (�). The source bytes are unchanged.

Reports omit timestamps unless the caller supplies timestamp: (a Time or RFC 3339 string). All three LensCore renderers accept the same report:

report = Postscript.validate("{ unclosed", level: 1, engine: :ruby)
puts LensCore::Renderers::Json.render(report)
puts LensCore::Renderers::Yaml.render(report)
puts LensCore::Renderers::Human.render(report)

Json output:

{
  "schema_version": 1,
  "producer": {
    "name": "postscript",
    "version": "0.2.1"
  },
  "profile": {
    "id": "postscript-level-1",
    "citations": [
      {
        "uri": "https://www.adobe.com/products/postscript/pdfs/PLRM.pdf",
        "label": "PLRM 3rd ed.: LanguageLevel 1"
      }
    ]
  },
  "valid": false,
  "summary": {
    "errors": 1,
    "warnings": 0,
    "infos": 0
  },
  "diagnostics": [
    {
      "severity": "error",
      "kind": "grammar",
      "requirement_id": "postscript.grammar.syntax",
      "message": "unbalanced procedure braces",
      "citations": [
        {
          "uri": "https://www.adobe.com/products/postscript/pdfs/PLRM.pdf",
          "label": "PLRM 3rd ed.: LanguageLevel 1"
        }
      ],
      "context": {
        "column": 1,
        "engine": "ruby",
        "expected": [],
        "line": 1,
        "offset": 0,
        "rule": null
      }
    }
  ]
}

Yaml output:

---
schema_version: 1
producer:
  name: postscript
  version: 0.2.1
profile:
  id: postscript-level-1
  citations:
  - uri: https://www.adobe.com/products/postscript/pdfs/PLRM.pdf
    label: 'PLRM 3rd ed.: LanguageLevel 1'
valid: false
summary:
  errors: 1
  warnings: 0
  infos: 0
diagnostics:
- severity: error
  kind: grammar
  requirement_id: postscript.grammar.syntax
  message: unbalanced procedure braces
  citations:
  - uri: https://www.adobe.com/products/postscript/pdfs/PLRM.pdf
    label: 'PLRM 3rd ed.: LanguageLevel 1'
  context:
    column: 1
    engine: ruby
    expected: []
    line: 1
    offset: 0
    rule:

Human output:

postscript 0.2.1, profile postscript-level-1
INVALID: 1 error, 0 warnings, 0 infos

error  postscript.grammar.syntax  (grammar)
  unbalanced procedure braces
  see: PLRM 3rd ed.: LanguageLevel 1 https://www.adobe.com/products/postscript/pdfs/PLRM.pdf
  context: {"column":1,"engine":"ruby","expected":[],"line":1,"offset":0,"rule":null}

Architecture

Three layers, each with a single responsibility:

Layer Owns

Postscript::Source

PS source → tokens → Model::Program. Lexer is comment-aware.

Postscript::Model

Typed PS records: Program, Literals::*, Operators::* (one class per PS operator).

Postscript::Serializer

Model::Program → PS source text.

Adding a new PS operator = writing one subclass + one visit_* method. No switch edits (OCP).

Value types

This gem also hosts three general-purpose value types that postsvg depends on:

  • Postscript::Matrix — 2D affine transform.

  • Postscript::Color — RGB / Gray / CMYK immutable value.

  • Postscript::FormatNumber — float → PS-safe text.

License

BSD-2-Clause. See LICENSE.