lib/LaTeXML/Core/Stomach.pm

filter: Statementstmt 95.5% 43 / 45 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 15 / 15 Podpod n/a totaltotal 96.6% 58 / 60 CC 1 SCAR 0.2
CC
1
Cov
96%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« lib/LaTeXML.pm ↑ Summary lib/LaTeXML/Package.pm »
1 # /=====================================================================\ #
2 # | LaTeXML::Core::Stomach | #
3 # | Analog of TeX's Stomach: digests tokens, stores state | #
4 # |=====================================================================| #
5 # | Part of LaTeXML: | #
6 # | Public domain software, produced as part of work done by the | #
7 # | United States Government & not subject to copyright in the US. | #
8 # |---------------------------------------------------------------------| #
9 # | Bruce Miller <bruce.miller@nist.gov> #_# | #
10 # | http://dlmf.nist.gov/LaTeXML/ (o o) | #
11 # \=========================================================ooo==U==ooo=/ #
12  
13 package LaTeXML::Core::Stomach;
14 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 5 ▶use LaTeXML::Global;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 5 ▶use LaTeXML::Common::Object;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 5 ▶use LaTeXML::Common::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 5 ▶use LaTeXML::Core::Token;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 5 ▶use LaTeXML::Core::Tokens;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 5 ▶use LaTeXML::Core::Gullet;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 5 ▶use LaTeXML::Core::Box;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 5 ▶use LaTeXML::Core::Comment;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 5 ▶use LaTeXML::Core::List;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 5 ▶use LaTeXML::Core::Mouth;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 5 ▶use LaTeXML::Common::Font;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 # Silly place to import these....?
28 5 ▶use LaTeXML::Common::Color;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 5 ▶use LaTeXML::Core::Definition;
Subroutine BEGIN: called CC=1 SCAR=2.6
30 use Scalar::Util qw(blessed);
31 use base qw(LaTeXML::Common::Object);
32  
33 #**********************************************************************
34 sub new {
35 my ($class, %options) = @_;
36 return bless { gullet => LaTeXML::Core::Gullet->new(%options),
37 boxing => [], token_stack => [] }, $class; }
38  
39 #**********************************************************************
40 # Initialize various parameters, preload, etc.
41 sub initialize {
42 my ($self) = @_;
43 $$self{boxing} = [];
44 $$self{token_stack} = [];
45 $$self{progress} = 0;
46 $STATE->assignValue(MODE => 'text', 'global');
47 $STATE->assignValue(IN_MATH => 0, 'global');
48 $STATE->assignValue(PRESERVE_NEWLINES => 1, 'global');
49 $STATE->assignValue(afterGroup => [], 'global');
50 $STATE->assignValue(afterAssignment => undef, 'global');
51 $STATE->assignValue(groupInitiator => 'Initialization', 'global');
52 # Setup default fonts.
53 $STATE->assignValue(font => LaTeXML::Common::Font->textDefault(), 'global');
54 $STATE->assignValue(mathfont => LaTeXML::Common::Font->mathDefault(), 'global');
55 return; }
56  
57 our $DIGESTION_PROGRESS_QUANTUM = 30000;
58  
59 #**********************************************************************
60 sub getGullet {
61 my ($self) = @_;
62 return $$self{gullet}; }
63  
64 sub getLocator {
65 my ($self) = @_;
66 return $$self{gullet}->getLocator; }
67  
68 sub getBoxingLevel {
69 my ($self) = @_;
70 return scalar(@{ $$self{boxing} }); }
71  
72 # ScriptLevel is similar to boxing level, but relative to current Math mode's level
73 # This is used for the scriptpos attribute to recognize overlapping sccripts.
74 # Making it relative to the math's level avoids unnecessary changes
75 sub getScriptLevel {
76 my ($self) = @_;
77 my $boxlevel = scalar(@{ $$self{boxing} });
78 if (my $prevlevel = $STATE->lookupValue('script_base_level')) {
79 return $boxlevel - $prevlevel + 1; }
80 else {
81 return $boxlevel; } }
82  
83 #**********************************************************************
84 # Digestion
85 #**********************************************************************
86 # NOTE: Worry about whether the $autoflush thing is right?
87 # It puts a lot of cruft in Gullet; Should we just create a new Gullet?
88  
89 sub digestNextBody {
90 my ($self, $terminal) = @_;
91 no warnings 'recursion';
92 my $startloc = $self->getLocator;
93 my $initdepth = scalar(@{ $$self{boxing} });
94 my $token;
95 local @LaTeXML::LIST = ();
96 my $alignment = $STATE->lookupValue('Alignment');
97 my @aug = ();
98  
99 while (defined($token = $$self{gullet}->readXToken(1, 1))) { # Done if we run out of tokens
100 my @r = $self->invokeToken($token);
101 push(@LaTeXML::LIST, @r);
102 push(@aug, $token, @r);
103 last if $terminal and Equals($token, $terminal);
104 last if $initdepth > scalar(@{ $$self{boxing} }); } # if we've closed the initial mode.
105 Warn('expected', $terminal, $self, "body should have ended with '" . ToString($terminal) . "'",
106 "current body started at " . ToString($startloc),
107 "Got " . join("\n -- ", map { Stringify($_) } @aug))
108 if $terminal && !Equals($token, $terminal);
109 push(@LaTeXML::LIST, Box()) unless $token; # Dummy `trailer' if none explicit.
110 return @LaTeXML::LIST; }
111  
112 # Digest a list of tokens independent from any current Gullet.
113 # Typically used to digest arguments to primitives or constructors.
114 # Returns a List containing the digested material.
115 sub digest {
116 my ($self, $tokens) = @_;
117 no warnings 'recursion';
118 return unless defined $tokens;
119 return
120 $$self{gullet}->readingFromMouth(LaTeXML::Core::Mouth->new(), sub {
121 my ($gullet) = @_;
122 $gullet->unread($tokens);
123 $STATE->clearPrefixes; # prefixes shouldn't apply here.
124 my $ismath = $STATE->lookupValue('IN_MATH');
125 my $initdepth = scalar(@{ $$self{boxing} });
126 local @LaTeXML::LIST = ();
127 while (defined(my $token = $$self{gullet}->readXToken(1, 1))) { # Done if we run out of tokens
128 push(@LaTeXML::LIST, $self->invokeToken($token));
129 last if $initdepth > scalar(@{ $$self{boxing} }); } # if we've closed the initial mode.
130 List(@LaTeXML::LIST, mode => ($ismath ? 'math' : 'text'));
131 }); }
132  
133 # Invoke a token;
134 # If it is a primitive or constructor, the definition will be invoked,
135 # possibly arguments will be parsed from the Gullet.
136 # Otherwise, the token is simply digested: turned into an appropriate box.
137 # Returns a list of boxes/whatsits.
138 my $MAXSTACK = 200; # [CONSTANT]
139  
140 # Overly complex, but want to avoid recursion/stack
141 our @CATCODE_ABSORBABLE = ( # [CONSTANT]
142 0, 0, 0, 0,
143 0, 0, 0, 0,
144 0, 0, 1, 1,
145 1, 0, 1, 0,
146 0, 0, 0, 0);
147  
148 sub invokeToken {
149 my ($self, $token) = @_;
150 no warnings 'recursion';
151 INVOKE:
152 ProgressStep() if ($$self{progress}++ % $DIGESTION_PROGRESS_QUANTUM) == 0;
153 push(@{ $$self{token_stack} }, $token);
154 if (scalar(@{ $$self{token_stack} }) > $MAXSTACK) {
155 Fatal('internal', '<recursion>', $self,
156 "Excessive recursion(?): ",
157 "Tokens on stack: " . join(', ', map { ToString($_) } @{ $$self{token_stack} })); }
158 local $LaTeXML::CURRENT_TOKEN = $token;
159 my @result = ();
160 my $meaning = $STATE->lookupDigestableDefinition($token);
161  
162 if (!$meaning) {
163 @result = $self->invokeToken_undefined($token); }
164 elsif ($meaning->isaToken) { # Common case
165 my $cc = $meaning->getCatcode;
166 if ($cc == CC_CS) {
167 @result = $self->invokeToken_undefined($token); }
168 elsif ($CATCODE_ABSORBABLE[$cc]) {
169 @result = $self->invokeToken_simple($token, $meaning); }
170 else {
171 # Special error guard for the align char "&":
172 # Locally deactivate to avoid a flurry of errors in the same table.
173 # Alert the end user once per table, allowing longer documents to not
174 # hit 100 errors too quickly.
175 $STATE->assignMeaning($token,
176 $STATE->lookupMeaning(T_CS('\relax')), 'local')
177 if Equals($token, T_ALIGN);
178 Error('misdefined', $token, $self,
179 "The token " . Stringify($token) . " should never reach Stomach!");
180 @result = $self->invokeToken_simple($token, $meaning); } }
181 # A math-active character will (typically) be a macro,
182 # but it isn't expanded in the gullet, but later when digesting, in math mode (? I think)
183 elsif ($meaning->isExpandable) {
184 my $gullet = $$self{gullet};
185 $gullet->unread($meaning->invoke($gullet));
186 $token = $gullet->readXToken(); # replace the token by it's expansion!!!
187 pop(@{ $$self{token_stack} });
188 goto INVOKE if $token; }
189 elsif ($meaning->isaDefinition) { # Otherwise, a normal primitive or constructor
190 @result = $meaning->invoke($self);
191 $STATE->clearPrefixes unless $meaning->isPrefix; } # Clear prefixes unless we just set one.
192 else {
193 Error('misdefined', $meaning, $self,
194 "The object " . Stringify($meaning) . " should never reach Stomach!");
195 @result = (makeMisdefinedError($meaning)); }
196 if ((scalar(@result) == 1) && (!defined $result[0])) {
197 @result = (); } # Just paper over the obvious thing.
198 if (my @bad = grep { (!blessed $_) || (!$_->isaBox) } @result) {
199 Error('misdefined', $token, $self,
200 "Execution yielded non boxes",
201 "Returned " . join(',', map { "'" . Stringify($_) . "'" } @bad));
202 @result = (makeMisdefinedError(@result)); }
203 pop(@{ $$self{token_stack} });
204 return @result; }
205  
206 sub makeMisdefinedError {
207 my (@objects) = @_;
208 return LaTeXML::Core::Whatsit->new($STATE->lookupDefinition(T_CS('\@ERROR')),
209 ['misdefined', join('', map { ToString($_); } @objects)],
210 font => $STATE->lookupValue('font'),
211 ); }
212  
213 sub invokeToken_undefined {
214 my ($self, $token) = @_;
215 $STATE->generateErrorStub($self, $token);
216 $self->getGullet->unread($token); # Retry
217 return; }
218  
219 sub invokeToken_simple {
220 my ($self, $token, $meaning) = @_;
221 my $cc = $meaning->getCatcode;
222 my $font = $STATE->lookupValue('font');
223 $STATE->clearPrefixes; # prefixes shouldn't apply here.
224 if ($cc == CC_SPACE) {
225 if ($STATE->lookupValue('IN_MATH')) { # (but in Preamble, OK ?)
226 return (); }
227 else {
228 return Box($meaning->toString, $font, $self->getGullet->getLocator, $meaning); } }
229 elsif ($cc == CC_COMMENT) { # Note: Comments need char decoding as well!
230 my $comment = LaTeXML::Package::FontDecodeString($meaning->toString, undef, 1);
231 # However, spaces normally would have be digested away as positioning...
232 my $badspace = pack('U', 0xA0) . "\x{0335}"; # This is at space's pos in OT1
233 $comment =~ s/\Q$badspace\E/ /g;
234 return LaTeXML::Core::Comment->new($comment); }
235 else {
236 return Box(LaTeXML::Package::FontDecodeString($meaning->toString, undef, 1),
237 undef, undef, $meaning); } }
238  
239 # Regurgitate: steal the previously digested boxes from the current level.
240 sub regurgitate {
241 my ($self) = @_;
242 my @stuff = @LaTeXML::LIST;
243 @LaTeXML::LIST = ();
244 return @stuff; }
245  
246 #**********************************************************************
247 # Maintaining State.
248 #**********************************************************************
249 # State changes that the Stomach needs to moderate and know about (?)
250  
251 #======================================================================
252 # Dealing with TeX's bindings & grouping.
253 # Note that lookups happen more often than bgroup/egroup (which open/close frames).
254  
255 sub pushStackFrame {
256 my ($self, $nobox) = @_;
257 $STATE->pushFrame;
258 $STATE->assignValue(beforeAfterGroup => [], 'local'); # ALWAYS bind this!
259 $STATE->assignValue(afterGroup => [], 'local'); # ALWAYS bind this!
260 $STATE->assignValue(afterAssignment => undef, 'local'); # ALWAYS bind this!
261 $STATE->assignValue(groupNonBoxing => $nobox, 'local'); # ALWAYS bind this!
262 $STATE->assignValue(groupInitiator => $LaTeXML::CURRENT_TOKEN, 'local');
263 $STATE->assignValue(groupInitiatorLocator => $self->getLocator, 'local');
264 push(@{ $$self{boxing} }, $LaTeXML::CURRENT_TOKEN) unless $nobox; # For begingroup/endgroup
265 return; }
266  
267 sub popStackFrame {
268 my ($self, $nobox) = @_;
269 if (my $beforeafter = $STATE->lookupValue('beforeAfterGroup')) {
270 if (@$beforeafter) {
271 my @result = map { $_->beDigested($self) } @$beforeafter;
272 if (my ($x) = grep { !$_->isaBox } @result) {
273 Error('misdefined', $x, $self, "Expected a Box|List|Whatsit, but got '" . Stringify($x) . "'");
274 @result = (makeMisdefinedError(@result)); }
275 push(@LaTeXML::LIST, @result); } }
276 my $after = $STATE->lookupValue('afterGroup');
277 $STATE->popFrame;
278 pop(@{ $$self{boxing} }) unless $nobox; # For begingroup/endgroup
279 $$self{gullet}->unread(@$after) if $after;
280 return; }
281  
282 sub currentFrameMessage {
283 my ($self) = @_;
284 return "current frame is "
285 . ($STATE->isValueBound('MODE', 0) # SET mode in CURRENT frame ?
286 ? "mode-switch to " . $STATE->lookupValue('MODE')
287 : ($STATE->lookupValue('groupNonBoxing') # Current frame is a non-boxing group?
288 ? "non-boxing" : "boxing") . " group")
289 . " due to " . Stringify($STATE->lookupValue('groupInitiator'))
290 . " " . ToString($STATE->lookupValue('groupInitiatorLocator')); }
291  
292 #======================================================================
293 # Grouping pushes a new stack frame for binding definitions, etc.
294 #======================================================================
295 # Originally, we only treated math vs text "modes", which are correlated
296 # to grouping (somehow). But we'll gradually need to incorporate all
297 # the horizontal/vertical modes, which are NOT correlated to grouping,
298 # although they do operate on a stack.
299 # So, we should NOT generate errors when the grouping clashes with modes
300 # (until we can get it properly sorted).
301  
302 # if $nobox is true, inhibit incrementing the boxingLevel
303 sub bgroup {
304 my ($self) = @_;
305 pushStackFrame($self, 0);
306 # NOTE: This is WRONG; should really only track "scanned" (not digested) braces
307 # Alas, there're too many code structuring differences between TeX and LaTeXML
308 # to find all the places to manage it.
309 # So, let's try this for now...
310 $LaTeXML::ALIGN_STATE++;
311 return; }
312  
313 sub egroup {
314 my ($self) = @_;
315 if ( ##$STATE->isValueBound('MODE', 0) || # Last stack frame was a mode switch!?!?!
316 $STATE->lookupValue('groupNonBoxing')) { # or group was opened with \begingroup
317 Error('unexpected', $LaTeXML::CURRENT_TOKEN, $self, "Attempt to close boxing group",
318 $self->currentFrameMessage); }
319 else { # Don't pop if there's an error; maybe we'll recover?
320 popStackFrame($self, 0); }
321 $LaTeXML::ALIGN_STATE--;
322 return; }
323  
324 sub begingroup {
325 my ($self) = @_;
326 pushStackFrame($self, 1);
327 return; }
328  
329 sub endgroup {
330 my ($self) = @_;
331 if ( ##$STATE->isValueBound('MODE', 0) || # Last stack frame was a mode switch!?!?!
332 !$STATE->lookupValue('groupNonBoxing')) { # or group was opened with \bgroup
333 Error('unexpected', $LaTeXML::CURRENT_TOKEN, $self, "Attempt to close non-boxing group",
334 $self->currentFrameMessage); }
335 else { # Don't pop if there's an error; maybe we'll recover?
336 popStackFrame($self, 1); }
337 return; }
338  
339 #======================================================================
340 # Mode (minimal so far; math vs text)
341 # Could (should?) be taken up by Stomach by building horizontal, vertical or math lists ?
342  
343 # This sets the mode without doing any grouping (NOR does it stack the modes!!)
344 # Useful for environments, where the group has already been established.
345 # (presumably, in the long run, modes & groups should be much less coupled)
346 sub setMode {
347 my ($self, $mode) = @_;
348 my $prevmode = $STATE->lookupValue('MODE');
349 my $ismath = $mode =~ /math$/;
350 $STATE->assignValue(MODE => $mode, 'local');
351 $STATE->assignValue(IN_MATH => $ismath, 'local');
352 my $curfont = $STATE->lookupValue('font');
353 if ($mode eq $prevmode) { }
354 elsif ($ismath) {
355 # When entering math mode, we set the font to the default math font,
356 # and save the text font for any embedded text.
357 $STATE->assignValue(savedfont => $curfont, 'local');
358 $STATE->assignValue(script_base_level => scalar(@{ $$self{boxing} })); # See getScriptLevel
359 $STATE->assignValue(font => $STATE->lookupValue('mathfont')->merge(
360 color => $curfont->getColor, background => $curfont->getBackground,
361 size => $curfont->getSize,
362 mathstyle => ($mode =~ /^display/ ? 'display' : 'text')), 'local'); }
363 else {
364 # When entering text mode, we should set the font to the text font in use before the math
365 # but inherit color and size
366 $STATE->assignValue(font => $STATE->lookupValue('savedfont')->merge(
367 color => $curfont->getColor, background => $curfont->getBackground,
368 size => $curfont->getSize), 'local'); }
369 return; }
370  
371 sub beginMode {
372 my ($self, $mode) = @_;
373 $self->pushStackFrame; # Effectively bgroup
374 $self->setMode($mode);
375 return; }
376  
377 sub endMode {
378 my ($self, $mode) = @_;
379 if ((!$STATE->isValueBound('MODE', 0)) # Last stack frame was NOT a mode switch!?!?!
380 || ($STATE->lookupValue('MODE') ne $mode)) { # Or was a mode switch to a different mode
381 Error('unexpected', $LaTeXML::CURRENT_TOKEN, $self, "Attempt to end mode $mode",
382 $self->currentFrameMessage); }
383 else { # Don't pop if there's an error; maybe we'll recover?
384 $self->popStackFrame; } # Effectively egroup.
385 return; }
386  
387 #**********************************************************************
388 1;
389  
390 __END__
« lib/LaTeXML.pm ↑ Summary lib/LaTeXML/Package.pm »