postscript 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -41,7 +41,7 @@ module Postscript
41
41
  # Returns true if the program body already contains a +showpage+
42
42
  # operator, so the serializer doesn't append a duplicate.
43
43
  def body_has_showpage?
44
- program.body.any? { |s| s.is_a?(Model::Operators::Device::Showpage) }
44
+ program.body.any?(Model::Operators::Device::Showpage)
45
45
  end
46
46
 
47
47
  # All methods below this point are public. They are intentionally
@@ -114,13 +114,57 @@ module Postscript
114
114
  end
115
115
  end
116
116
 
117
+ # Inline form for nodes nested inside an array, dictionary or
118
+ # procedure: composites recurse, operators and name references
119
+ # emit their keyword. Covers every node the AstBuilder can place
120
+ # in a composite, so round-trips lose nothing.
117
121
  def emit_inline(statement, buffer)
118
122
  case statement
119
- when Model::Literals::Number then buffer << FormatNumber.call(statement.value)
120
- when Model::Literals::Name then buffer << (statement.literal? ? "/" : "") << statement.value
121
- when Model::Literals::StringLiteral then buffer << escape_string(statement.value)
122
- when Model::Literals::HexLiteral then buffer << "<" << statement.value << ">"
123
- else buffer << statement.class.name.to_s
123
+ when Model::Literals::Number
124
+ buffer << FormatNumber.call(statement.value)
125
+ when Model::Literals::Name
126
+ buffer << (statement.literal? ? "/" : "") << statement.value
127
+ when Model::Literals::StringLiteral
128
+ buffer << escape_string(statement.value)
129
+ when Model::Literals::HexLiteral
130
+ buffer << "<" << statement.value << ">"
131
+ when Model::Literals::ArrayLiteral, Model::Literals::Dictionary,
132
+ Model::Literals::Procedure
133
+ emit_inline_composite(statement, buffer)
134
+ when Model::InvokeProcedure
135
+ buffer << statement.name
136
+ when Model::Operator, Model::UnknownOperator
137
+ buffer << statement.keyword
138
+ else
139
+ raise SerializeError, "cannot serialize #{statement.class} inline"
140
+ end
141
+ end
142
+
143
+ # Bracketed composites nest: elements recurse through emit_inline.
144
+ def emit_inline_composite(statement, buffer)
145
+ case statement
146
+ when Model::Literals::ArrayLiteral
147
+ buffer << "[ "
148
+ statement.elements.each do |element|
149
+ emit_inline(element, buffer)
150
+ buffer << " "
151
+ end
152
+ buffer << "]"
153
+ when Model::Literals::Dictionary
154
+ buffer << "<< "
155
+ statement.entries.each do |key, value|
156
+ buffer << "/" << key << " "
157
+ emit_inline(value, buffer)
158
+ buffer << " "
159
+ end
160
+ buffer << ">>"
161
+ when Model::Literals::Procedure
162
+ buffer << "{ "
163
+ statement.body.each do |inner|
164
+ emit_inline(inner, buffer)
165
+ buffer << " "
166
+ end
167
+ buffer << "}"
124
168
  end
125
169
  end
126
170
 
@@ -140,6 +184,5 @@ module Postscript
140
184
  .gsub("\t", '\\t')
141
185
  "(#{escaped})"
142
186
  end
143
-
144
187
  end
145
188
  end
@@ -49,7 +49,7 @@ module Postscript
49
49
  collected
50
50
  end
51
51
 
52
- # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
52
+ # rubocop:disable-next Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
53
53
  def consume_token(token, collected)
54
54
  case token.type
55
55
  when :number
@@ -88,7 +88,6 @@ module Postscript
88
88
  1
89
89
  end
90
90
  end
91
- # rubocop:enable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
92
91
 
93
92
  # Push a literal onto both the parse stack and the program body.
94
93
  # The body is what the visitor walks; the stack is what operator
@@ -132,19 +131,23 @@ module Postscript
132
131
  end_index - start_index + 1
133
132
  end
134
133
 
134
+ # Consume a bracketed array literal. Every token between the
135
+ # brackets becomes an element: PostScript's "[ ... ]" is executed
136
+ # marking, so the array must keep operators (e.g. "[ 1 2 add ]")
137
+ # as well as literals, or the program loses information.
135
138
  def consume_array(after:, collected:)
136
139
  start_index = find_index(after)
137
140
  body_tokens, end_index = match_until(start_index + 1, :array_close,
138
141
  :array_open)
139
- body_nodes = sub_build(body_tokens)
140
- array = Model::Literals::ArrayLiteral.new(body_nodes.select do |n|
141
- literal?(n)
142
- end)
142
+ array = Model::Literals::ArrayLiteral.new(sub_build(body_tokens))
143
143
  @stack.push(array)
144
144
  append_statement(array, collected)
145
145
  end_index - start_index + 1
146
146
  end
147
147
 
148
+ # Consume an inline dictionary literal. The dictionary is recorded
149
+ # as a statement on the program body (as well as pushed onto the
150
+ # stack) so visitors and level checks see its entries.
148
151
  def consume_dict(after:, collected:)
149
152
  start_index = find_index(after)
150
153
  body_tokens, end_index = match_until(start_index + 1, :dict_close,
@@ -153,29 +156,19 @@ module Postscript
153
156
  pending_key = nil
154
157
  sub_nodes = sub_build(body_tokens)
155
158
  sub_nodes.each do |node|
156
- if node.is_a?(Model::Literals::Name) && node.literal?
157
- pending_key = node.value
158
- elsif pending_key
159
+ if pending_key
159
160
  entries[pending_key] = node
160
161
  pending_key = nil
162
+ elsif node.is_a?(Model::Literals::Name) && node.literal?
163
+ pending_key = node.value
161
164
  end
162
165
  end
163
166
  dict = Model::Literals::Dictionary.new(entries)
164
167
  @stack.push(dict)
165
- collected << dict
168
+ append_statement(dict, collected)
166
169
  end_index - start_index + 1
167
170
  end
168
171
 
169
- def literal?(node)
170
- node.is_a?(Model::Literals::Number) ||
171
- node.is_a?(Model::Literals::Name) ||
172
- node.is_a?(Model::Literals::StringLiteral) ||
173
- node.is_a?(Model::Literals::HexLiteral) ||
174
- node.is_a?(Model::Literals::ArrayLiteral) ||
175
- node.is_a?(Model::Literals::Procedure) ||
176
- node.is_a?(Model::Literals::Dictionary)
177
- end
178
-
179
172
  def sub_build(sub_tokens)
180
173
  # Build a temporary AstBuilder over a sub-token-stream and
181
174
  # harvest its body. The temp builder shares no state with the
@@ -207,7 +200,8 @@ module Postscript
207
200
  end
208
201
  i += 1
209
202
  end
210
- raise SyntaxError, "unbalanced procedure braces"
203
+ raise SyntaxError.new("unbalanced procedure braces",
204
+ source_position: token_position(tokens[start_index - 1]))
211
205
  end
212
206
 
213
207
  def match_until(start_index, close_type, open_type)
@@ -223,7 +217,8 @@ module Postscript
223
217
  end
224
218
  i += 1
225
219
  end
226
- raise SyntaxError, "unbalanced #{close_type}"
220
+ raise SyntaxError.new("unbalanced #{close_type}",
221
+ source_position: token_position(tokens[start_index - 1]))
227
222
  end
228
223
 
229
224
  def consume_operator(token, collected)
@@ -41,6 +41,52 @@ module Postscript
41
41
  new(source).tokenize
42
42
  end
43
43
 
44
+ # Escapes in a literal string that stand for one character. Any
45
+ # other escaped character stands for itself, except octal digits.
46
+ ESCAPES = {
47
+ "n" => "\n", "r" => "\r", "t" => "\t", "b" => "\b", "f" => "\f",
48
+ "\\" => "\\", "(" => "(", ")" => ")"
49
+ }.freeze
50
+
51
+ # The value of a literal string from the bytes between its outer
52
+ # parentheses: escapes expanded, \ddd octal (1-3 digits) taken
53
+ # modulo 256.
54
+ def self.decode_string(raw)
55
+ value = +""
56
+ index = 0
57
+ while index < raw.bytesize
58
+ byte = raw.getbyte(index)
59
+ index += 1
60
+ if byte == 92 && index < raw.bytesize # backslash
61
+ index = decode_escape(raw, index, value)
62
+ else
63
+ value << byte.chr
64
+ end
65
+ end
66
+ value
67
+ end
68
+
69
+ # The value of a hex string from the bytes between < and >.
70
+ def self.decode_hex(raw)
71
+ raw.delete("^0-9a-fA-F")
72
+ end
73
+
74
+ def self.decode_escape(raw, index, value)
75
+ char = raw.getbyte(index).chr
76
+ if (replacement = ESCAPES[char])
77
+ value << replacement
78
+ index + 1
79
+ elsif ("0".."7").cover?(char)
80
+ digits = raw.byteslice(index, 3)[/\A[0-7]+/]
81
+ value << (digits.to_i(8) & 0xFF).chr
82
+ index + digits.bytesize
83
+ else
84
+ value << char
85
+ index + 1
86
+ end
87
+ end
88
+ private_class_method :decode_escape
89
+
44
90
  private
45
91
 
46
92
  def eos? = @position >= @source.bytesize
@@ -73,19 +119,25 @@ module Postscript
73
119
  when "(" then start_string
74
120
  when "<"
75
121
  if peek(1) == 60 # <<
76
- advance
77
- advance
78
122
  emit(:dict_open, "<<")
79
123
  else
80
124
  start_hexstring
81
125
  end
82
126
  when ">" then maybe_close_dict
83
- when "{" then advance and emit(:proc_open, "{")
84
- when "}" then advance and emit(:proc_close, "}")
85
- when "[" then advance and emit(:array_open, "[")
86
- when "]" then advance and emit(:array_close, "]")
87
- when "/", "\\"
88
- start_name_with_slash(char)
127
+ when ")" then unbalanced_paren!
128
+ when "{" then emit(:proc_open, "{")
129
+ when "}" then emit(:proc_close, "}")
130
+ when "[" then emit(:array_open, "[")
131
+ when "]" then emit(:array_close, "]")
132
+ # Deviation, deliberate: a leading backslash also starts a
133
+ # literal name here, while the Guide starts literal names with
134
+ # "/" only (guide: docs/syntax/operators.adoc, "Literal Names";
135
+ # docs/syntax/tokens.adoc lists the delimiters without the
136
+ # backslash, so "\Name" would be an ordinary executable name).
137
+ # It matches the PARG grammar's literal_name rule
138
+ # ("/" / "\\"), and NativeLexer must produce exactly Lexer's
139
+ # tokens. Needs the same grammar change first (issue #26).
140
+ when "/", "\\" then start_name_with_slash
89
141
  else
90
142
  scan_word_or_number
91
143
  end
@@ -103,12 +155,26 @@ module Postscript
103
155
  consumed
104
156
  end
105
157
 
158
+ # Deviation, deliberate: this set includes VT (0x0B), which the
159
+ # Guide's whitespace list does not (guide: docs/syntax/tokens.adoc,
160
+ # "Whitespace" — only NUL HT LF FF CR SPACE). It matches the PARG
161
+ # grammar's ws rule (postscript-parg postscript.parg, "VT is
162
+ # included to match the lexer"), and NativeLexer must produce
163
+ # exactly Lexer's tokens; changing one side alone breaks that
164
+ # agreement. Needs the same grammar change first (issue #26).
106
165
  def whitespace_byte?(byte)
107
166
  byte && [32, 9, 10, 13, 12, 11, 0].include?(byte)
108
167
  end
109
168
 
110
169
  def start_dsc_or_comment
111
170
  advance # consume first %
171
+ # Deviation, deliberate: "%%" is recognised as a DSC comment in
172
+ # any context, while the Guide treats DSC comments as
173
+ # document-level lines (guide: docs/syntax/tokens.adoc,
174
+ # "Comments"). It matches the PARG grammar, which captures
175
+ # dsc_comment inside arrays, procedures and dictionaries like at
176
+ # top level, and NativeLexer must produce exactly Lexer's tokens.
177
+ # Needs the same grammar change first (issue #26).
112
178
  if peek == 37 # second %
113
179
  advance # consume second %
114
180
  @state = :dsc
@@ -121,6 +187,12 @@ module Postscript
121
187
  start_pos = @position
122
188
  start_line = @line
123
189
  start_col = @column
190
+ # Deviation, deliberate: only LF ends a DSC comment, while the
191
+ # Guide ends lines at CR, LF and CRLF (guide:
192
+ # docs/syntax/tokens.adoc, "Whitespace"/"Comments"). It matches
193
+ # the PARG grammar's dsc_comment rule ("Only LF ends it, as for
194
+ # comment"), and NativeLexer must produce exactly Lexer's tokens.
195
+ # Needs the same grammar change first (issue #26).
124
196
  advance until eos? || @source.getbyte(@position) == 10
125
197
  text = @source.byteslice(start_pos, @position - start_pos)
126
198
  @tokens << Model::Token.new(:dsc, text.chomp, line: start_line,
@@ -129,6 +201,9 @@ module Postscript
129
201
  end
130
202
 
131
203
  def scan_comment_body
204
+ # Deviation, deliberate: only LF ends a comment — see
205
+ # scan_dsc_body for the Guide citation and the grammar-parity
206
+ # rationale (issue #26).
132
207
  advance until eos? || @source.getbyte(@position) == 10
133
208
  @state = :top
134
209
  end
@@ -147,8 +222,9 @@ module Postscript
147
222
  byte = @source.getbyte(@position)
148
223
  advance
149
224
  case byte
150
- when 92 # backslash
151
- handle_escape
225
+ when 92 # backslash: kept raw, with the byte it escapes
226
+ @string_start[:bytes] << "\\"
227
+ @string_start[:bytes] << advance.chr unless eos?
152
228
  when 40 # (
153
229
  @string_depth += 1
154
230
  @string_start[:bytes] << "("
@@ -168,48 +244,9 @@ module Postscript
168
244
  @string_start[:column]])
169
245
  end
170
246
 
171
- def handle_escape
172
- byte = peek
173
- return if byte.nil?
174
-
175
- char = byte.chr
176
- replacement =
177
- case char
178
- when "n" then "\n"
179
- when "r" then "\r"
180
- when "t" then "\t"
181
- when "b" then "\b"
182
- when "f" then "\f"
183
- when "\\" then "\\"
184
- when "(" then "("
185
- when ")" then ")"
186
- when "0".."7"
187
- consume_octal_escape
188
- else
189
- char
190
- end
191
- return unless replacement.is_a?(String)
192
-
193
- advance
194
- @string_start[:bytes] << replacement
195
- end
196
-
197
- def consume_octal_escape
198
- digits = +""
199
- 3.times do
200
- byte = peek
201
- break unless byte && byte >= 48 && byte <= 55 # 0..7
202
-
203
- digits << byte.chr
204
- advance
205
- end
206
- code = digits.to_i(8) & 0xFF
207
- @string_start[:bytes] << code.chr
208
- nil
209
- end
210
-
211
247
  def emit_string
212
- @tokens << Model::Token.new(:string, @string_start[:bytes],
248
+ value = self.class.decode_string(@string_start[:bytes])
249
+ @tokens << Model::Token.new(:string, value,
213
250
  line: @string_start[:line], column: @string_start[:column])
214
251
  @string_start = nil
215
252
  @state = :top
@@ -223,6 +260,9 @@ module Postscript
223
260
  @state = :hexstring
224
261
  end
225
262
 
263
+ # Hex strings hold hex digits and whitespace only (guide:
264
+ # docs/syntax/tokens.adoc, "Hexadecimal Strings"); any other byte
265
+ # is a syntax error, not a character to drop.
226
266
  def scan_hexstring_body
227
267
  until eos?
228
268
  byte = @source.getbyte(@position)
@@ -234,6 +274,12 @@ module Postscript
234
274
  when 32, 9, 10, 13, 12
235
275
  advance
236
276
  else
277
+ unless hex_digit_byte?(byte)
278
+ raise LexError.new(
279
+ "invalid hex digit #{byte.chr.inspect} in a hex string",
280
+ source_position: [@line, @column],
281
+ )
282
+ end
237
283
  advance
238
284
  @hex_start[:bytes] << byte.chr
239
285
  end
@@ -243,26 +289,39 @@ module Postscript
243
289
  @hex_start[:column]])
244
290
  end
245
291
 
292
+ def hex_digit_byte?(byte)
293
+ (48..57).cover?(byte) || (65..70).cover?(byte) || (97..102).cover?(byte)
294
+ end
295
+
246
296
  def emit_hexstring
247
- hex = @hex_start[:bytes].delete("^0-9a-fA-F")
297
+ hex = self.class.decode_hex(@hex_start[:bytes])
248
298
  @tokens << Model::Token.new(:hexstring, hex,
249
299
  line: @hex_start[:line], column: @hex_start[:column])
250
300
  @hex_start = nil
251
301
  @state = :top
252
302
  end
253
303
 
304
+ # A ")" outside a string closes nothing. Every other delimiter is
305
+ # consumed above; this one would reach scan_word_or_number, which
306
+ # consumes no delimiter, and the lexer would never advance.
307
+ def unbalanced_paren!
308
+ raise LexError.new("unbalanced ')' outside a string literal",
309
+ source_position: [@line, @column])
310
+ end
311
+
254
312
  def maybe_close_dict
255
313
  if peek(1) == 62 # >>
256
- advance
257
- advance
258
314
  emit(:dict_close, ">>")
259
315
  else
260
- # Lone '>' is not a valid token in PS; skip and warn via token.
261
- advance
316
+ # The Guide has no lone ">" token: ">" closes a hex string,
317
+ # ">>" closes a dictionary; anywhere else it is a syntax
318
+ # error (guide: docs/syntax/tokens.adoc, "Token Delimiters").
319
+ raise LexError.new("unexpected '>'",
320
+ source_position: [@line, @column])
262
321
  end
263
322
  end
264
323
 
265
- def start_name_with_slash(_prefix)
324
+ def start_name_with_slash
266
325
  start_line = @line
267
326
  start_col = @column
268
327
  advance
@@ -274,6 +333,15 @@ module Postscript
274
333
  bytes << byte.chr
275
334
  advance
276
335
  end
336
+ # Deviation, deliberate: "//x" lexes as an empty literal name
337
+ # followed by "/x", while the Guide makes "//name" an
338
+ # immediately evaluated name (guide: docs/syntax/operators.adoc,
339
+ # "Immediately Evaluated Names"; docs/syntax/tokens.adoc). It
340
+ # matches the PARG grammar's literal_name rule ("the name may be
341
+ # empty: '//x' is an empty literal name followed by '/x'"), and
342
+ # NativeLexer must produce exactly Lexer's tokens; Guide shape
343
+ # also needs an immediate flag on Token and Model::Literals::Name
344
+ # first. Needs the same grammar change first (issue #26).
277
345
  @tokens << Model::Token.new(:name, bytes, line: start_line,
278
346
  column: start_col, literal: true)
279
347
  end
@@ -313,6 +381,7 @@ module Postscript
313
381
 
314
382
  def emit(type, value)
315
383
  @tokens << Model::Token.new(type, value, line: @line, column: @column)
384
+ value.bytesize.times { advance }
316
385
  end
317
386
  end
318
387
  end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Postscript
4
+ module Source
5
+ # The vendored PostScript grammar (grammars/postscript.json) on the
6
+ # parsanol native engine.
7
+ #
8
+ # parsanol is an optional dependency. It is loaded on first use; a
9
+ # missing, old, or extension-less install raises
10
+ # NativeEngineUnavailable rather than running parsanol's pure-Ruby
11
+ # runtime in its place.
12
+ module NativeEngine
13
+ MINIMUM_VERSION = "1.3.96"
14
+ ARTIFACT = File.expand_path("../../../grammars/postscript.json",
15
+ __dir__)
16
+ ENTRY = "main"
17
+
18
+ class << self
19
+ # Whether engine: :native can run here.
20
+ def available?
21
+ artifact
22
+ true
23
+ rescue NativeEngineUnavailable
24
+ false
25
+ end
26
+
27
+ # The capture tree for UTF-8 +input+, or nil when the grammar
28
+ # rejects it.
29
+ def parse(input)
30
+ # Loaded first: until parsanol is, Parsanol::ParseFailed is not
31
+ # a constant the rescue below can name.
32
+ grammar = artifact
33
+ begin
34
+ grammar.parse(ENTRY, input)
35
+ rescue Parsanol::ParseFailed
36
+ nil
37
+ end
38
+ end
39
+
40
+ # A native grammar failure in UTF-8 input byte coordinates, or nil
41
+ # on success. Older artifacts expose the same data on the cause.
42
+ def diagnose(input)
43
+ grammar = artifact
44
+ result = if grammar.respond_to?(:parse_with_diagnostics)
45
+ grammar.parse_with_diagnostics(ENTRY, input)
46
+ else
47
+ diagnose_failure(grammar, input)
48
+ end
49
+ return if result["ok"]
50
+
51
+ diagnostic(result)
52
+ end
53
+
54
+ # Raises NativeEngineUnavailable unless parsanol +version+ is
55
+ # recent enough and its +native+ extension loaded.
56
+ def check!(version, native:)
57
+ if Gem::Version.new(version) < Gem::Version.new(MINIMUM_VERSION)
58
+ unavailable!("needs parsanol >= #{MINIMUM_VERSION}, " \
59
+ "found #{version}")
60
+ end
61
+ return if native
62
+
63
+ unavailable!("parsanol #{version} has no native extension " \
64
+ "for this platform")
65
+ end
66
+
67
+ private
68
+
69
+ def diagnostic(result)
70
+ message = Array(result["message"]).join
71
+ expected = Array(result["expected"])
72
+ expected = message_labels(message) if expected.empty?
73
+ { offset: result["offset"], expected: expected, message: message,
74
+ rule: result["rule"] || ENTRY }
75
+ end
76
+
77
+ def diagnose_failure(grammar, input)
78
+ grammar.parse(ENTRY, input)
79
+ { "ok" => true }
80
+ rescue Parsanol::ParseFailed => e
81
+ cause = deepest_cause(e.parse_failure_cause)
82
+ { "ok" => false, "offset" => cause&.position,
83
+ "expected" => cause.respond_to?(:expected) ? cause.expected : [],
84
+ "message" => cause&.message || e.message,
85
+ "rule" => cause.respond_to?(:rule) ? cause.rule : nil }
86
+ end
87
+
88
+ def deepest_cause(cause)
89
+ return cause if cause.nil? || cause.children.empty?
90
+
91
+ deepest = cause.children.map { |child| deepest_cause(child) }
92
+ .max_by { |child| child.position.to_i }
93
+ deepest.position.to_i >= cause.position.to_i ? deepest : cause
94
+ end
95
+
96
+ # Some releases wrap native labels only in Cause#message, leaving
97
+ # the structured expected list empty. Keep the PARG labels verbatim.
98
+ def message_labels(message)
99
+ labels = message[/\AFailed to match: expected one of \[(.*)\]\z/m, 1]
100
+ labels ? labels.split(", ") : []
101
+ end
102
+
103
+ def artifact
104
+ @artifact ||= begin
105
+ load_parsanol
106
+ Parsanol::PARG::Artifact.load(ARTIFACT)
107
+ end
108
+ end
109
+
110
+ def load_parsanol
111
+ require "parsanol"
112
+ rescue LoadError
113
+ unavailable!("needs the parsanol gem (>= #{MINIMUM_VERSION}, " \
114
+ "Ruby >= 3.2)")
115
+ else
116
+ check!(Parsanol::VERSION, native: Parsanol::Native.available?)
117
+ end
118
+
119
+ def unavailable!(reason)
120
+ raise NativeEngineUnavailable, "engine: :native #{reason}"
121
+ end
122
+ end
123
+ end
124
+ end
125
+ end