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/Package.pm ↑ Summary lib/LaTeXML/Global.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 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 4 ▶use LaTeXML::Global;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 4 ▶use LaTeXML::Common::Object;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 4 ▶use LaTeXML::Common::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 4 ▶use LaTeXML::Core::Token;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 4 ▶use LaTeXML::Core::Tokens;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 4 ▶use LaTeXML::Core::Gullet;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 4 ▶use LaTeXML::Core::Box;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 4 ▶use LaTeXML::Core::Comment;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 4 ▶use LaTeXML::Core::List;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 4 ▶use LaTeXML::Core::Mouth;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 4 ▶use LaTeXML::Common::Font;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 # Silly place to import these....?
28 4 ▶use LaTeXML::Common::Color;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 4 ▶use LaTeXML::Core::Definition;
Subroutine BEGIN: called CC=1 SCAR=2.6
30 use base qw(LaTeXML::Common::Object);
31  
32 #**********************************************************************
33 sub new {
34 my ($class, %options) = @_;
35 return bless { gullet => LaTeXML::Core::Gullet->new(),
36 boxing => [], token_stack => [] }, $class; }
37  
38 #**********************************************************************
39 # Initialize various parameters, preload, etc.
40 sub initialize {
41 my ($self) = @_;
42 $$self{boxing} = [];
43 $$self{token_stack} = [];
44 $STATE->assignValue(MODE => 'text', 'global');
45 $STATE->assignValue(IN_MATH => 0, 'global');
46 $STATE->assignValue(PRESERVE_NEWLINES => 1, 'global');
47 $STATE->assignValue(afterGroup => [], 'global');
48 $STATE->assignValue(afterAssignment => undef, 'global');
49 $STATE->assignValue(groupInitiator => 'Initialization', 'global');
50 # Setup default fonts.
51 $STATE->assignValue(font => LaTeXML::Common::Font->textDefault(), 'global');
52 $STATE->assignValue(mathfont => LaTeXML::Common::Font->mathDefault(), 'global');
53 return; }
54  
55 #**********************************************************************
56 sub getGullet {
57 my ($self) = @_;
58 return $$self{gullet}; }
59  
60 sub getLocator {
61 my ($self) = @_;
62 return $$self{gullet}->getLocator; }
63  
64 sub getBoxingLevel {
65 my ($self) = @_;
66 return scalar(@{ $$self{boxing} }); }
67  
68 # ScriptLevel is similar to boxing level, but relative to current Math mode's level
69 # This is used for the scriptpos attribute to recognize overlapping sccripts.
70 # Making it relative to the math's level avoids unnecessary changes
71 sub getScriptLevel {
72 my ($self) = @_;
73 my $boxlevel = scalar(@{ $$self{boxing} });
74 if (my $prevlevel = $STATE->lookupValue('script_base_level')) {
75 return $boxlevel - $prevlevel + 1; }
76 else {
77 return $boxlevel; } }
78  
79 #**********************************************************************
80 # Digestion
81 #**********************************************************************
82 # NOTE: Worry about whether the $autoflush thing is right?
83 # It puts a lot of cruft in Gullet; Should we just create a new Gullet?
84  
85 sub digestNextBody {
86 my ($self, $terminal) = @_;
87 no warnings 'recursion';
88 my $startloc = $self->getLocator;
89 my $initdepth = scalar(@{ $$self{boxing} });
90 my $token;
91 local @LaTeXML::LIST = ();
92 while (defined($token = $$self{gullet}->readXToken(1, 1))) { # Done if we run out of tokens
93 push(@LaTeXML::LIST, $self->invokeToken($token));
94 last if $terminal and Equals($token, $terminal);
95 last if $initdepth > scalar(@{ $$self{boxing} }); } # if we've closed the initial mode.
96 Warn('expected', $terminal, $self, "body should have ended with '" . ToString($terminal) . "'",
97 "current body started at " . ToString($startloc))
98 if $terminal && !Equals($token, $terminal);
99 push(@LaTeXML::LIST, Box()) unless $token; # Dummy `trailer' if none explicit.
100 return @LaTeXML::LIST; }
101  
102 # Digest a list of tokens independent from any current Gullet.
103 # Typically used to digest arguments to primitives or constructors.
104 # Returns a List containing the digested material.
105 sub digest {
106 my ($self, $tokens) = @_;
107 no warnings 'recursion';
108 return unless defined $tokens;
109 return
110 $$self{gullet}->readingFromMouth(LaTeXML::Core::Mouth->new(), sub {
111 my ($gullet) = @_;
112 $gullet->unread($tokens);
113 $STATE->clearPrefixes; # prefixes shouldn't apply here.
114 my $ismath = $STATE->lookupValue('IN_MATH');
115 my $initdepth = scalar(@{ $$self{boxing} });
116 my $depth = $initdepth;
117 local @LaTeXML::LIST = ();
118 while (defined(my $token = $$self{gullet}->readXToken(1, 1))) { # Done if we run out of tokens
119 push(@LaTeXML::LIST, $self->invokeToken($token));
120 last if $initdepth > scalar(@{ $$self{boxing} }); } # if we've closed the initial mode.
121 Fatal('internal', '<EOF>', $self,
122 "We've fallen off the end, somehow!?!?!",
123 "Last token " . ToString($LaTeXML::CURRENT_TOKEN)
124 . " (Boxing depth was $initdepth, now $depth: Boxing generated by "
125 . join(', ', map { ToString($_) } @{ $$self{boxing} }))
126 if $initdepth < $depth;
127  
128 List(@LaTeXML::LIST, mode => ($ismath ? 'math' : 'text'));
129 }); }
130  
131 # Invoke a token;
132 # If it is a primitive or constructor, the definition will be invoked,
133 # possibly arguments will be parsed from the Gullet.
134 # Otherwise, the token is simply digested: turned into an appropriate box.
135 # Returns a list of boxes/whatsits.
136 my $MAXSTACK = 200; # [CONSTANT]
137  
138 # Overly complex, but want to avoid recursion/stack
139 my @absorbable_cc = ( # [CONSTANT]
140 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0);
141  
142 sub invokeToken {
143 my ($self, $token) = @_;
144 no warnings 'recursion';
145 INVOKE:
146 push(@{ $$self{token_stack} }, $token);
147 if (scalar(@{ $$self{token_stack} }) > $MAXSTACK) {
148 Fatal('internal', '<recursion>', $self,
149 "Excessive recursion(?): ",
150 "Tokens on stack: " . join(', ', map { ToString($_) } @{ $$self{token_stack} })); }
151 local $LaTeXML::CURRENT_TOKEN = $token;
152 my @result = ();
153 my $meaning = $STATE->lookupDigestableDefinition($token);
154  
155 if ($meaning->isaToken) { # Common case
156 my $cc = $meaning->getCatcode;
157 if ($cc == CC_CS) {
158 @result = $self->invokeToken_undefined($token); }
159 elsif ($absorbable_cc[$cc]) {
160 @result = $self->invokeToken_simple($token, $meaning); }
161 else {
162 Error('misdefined', $token, $self,
163 "The token " . Stringify($token) . " should never reach Stomach!");
164 @result = $self->invokeToken_simple($token, $meaning); } }
165 # A math-active character will (typically) be a macro,
166 # but it isn't expanded in the gullet, but later when digesting, in math mode (? I think)
167 elsif ($meaning->isExpandable) {
168 my $gullet = $$self{gullet};
169 $gullet->unread(@{ $meaning->invoke($gullet) || [] });
170 $token = $gullet->readXToken(); # replace the token by it's expansion!!!
171 pop(@{ $$self{token_stack} });
172 goto INVOKE; }
173 elsif ($meaning->isaDefinition) { # Otherwise, a normal primitive or constructor
174 @result = $meaning->invoke($self);
175 $STATE->clearPrefixes unless $meaning->isPrefix; } # Clear prefixes unless we just set one.
176 else {
177 Fatal('misdefined', $meaning, $self,
178 "The object " . Stringify($meaning) . " should never reach Stomach!"); }
179 if ((scalar(@result) == 1) && (!defined $result[0])) {
180 @result = (); } # Just paper over the obvious thing.
181 Fatal('misdefined', $token, $self,
182 "Execution yielded non boxes",
183 "Returned " . join(',', map { "'" . Stringify($_) . "'" }
184 grep { (!ref $_) || (!$_->isaBox) } @result))
185 if grep { (!ref $_) || (!$_->isaBox) } @result;
186  
187 pop(@{ $$self{token_stack} });
188 return @result; }
189  
190 sub makeError {
191 my ($document, $type, $content) = @_;
192 my $savenode = undef;
193 $savenode = $document->floatToElement('ltx:ERROR')
194 unless $document->isOpenable('ltx:ERROR');
195 $document->openElement('ltx:ERROR', class => ToString($type));
196 $document->openText_internal(ToString($content));
197 $document->closeElement('ltx:ERROR');
198 $document->setNode($savenode) if $savenode;
199 return; }
200  
201 sub invokeToken_undefined {
202 my ($self, $token) = @_;
203 my $cs = $token->getCSName;
204 $STATE->noteStatus(undefined => $cs);
205 # To minimize chatter, go ahead and define it...
206 if ($cs =~ /^\\if(.*)$/) { # Apparently an \ifsomething ???
207 my $name = $1;
208 Error('undefined', $token, $self, "The token " . Stringify($token) . " is not defined.",
209 "Defining it now as with \\newif");
210 $STATE->installDefinition(LaTeXML::Core::Definition::Expandable->new(
211 T_CS('\\' . $name . 'true'), undef, '\let' . $cs . '\iftrue'));
212 $STATE->installDefinition(LaTeXML::Core::Definition::Expandable->new(
213 T_CS('\\' . $name . 'false'), undef, '\let' . $cs . '\iffalse'));
214 LaTeXML::Package::Let($token, T_CS('\iffalse'));
215 $self->getGullet->unread($token); # Retry
216 return; }
217 else {
218 Error('undefined', $token, $self, "The token " . Stringify($token) . " is not defined.",
219 "Defining it now as <ltx:ERROR/>");
220 $STATE->installDefinition(LaTeXML::Core::Definition::Constructor->new($token, undef,
221 sub { makeError($_[0], 'undefined', $cs); }),
222 'global');
223 # and then invoke it.
224 return $self->invokeToken($token); } }
225  
226 sub invokeToken_simple {
227 my ($self, $token, $meaning) = @_;
228 my $cc = $meaning->getCatcode;
229 my $font = $STATE->lookupValue('font');
230 $STATE->clearPrefixes; # prefixes shouldn't apply here.
231 if ($cc == CC_SPACE) {
232 if ($STATE->lookupValue('IN_MATH')) { # (but in Preamble, OK ?)
233 return (); }
234 else {
235 return Box($meaning->getString, $font, $self->getGullet->getLocator, $meaning); } }
236 elsif ($cc == CC_COMMENT) { # Note: Comments need char decoding as well!
237 my $comment = LaTeXML::Package::FontDecodeString($meaning->getString, undef, 1);
238 # However, spaces normally would have be digested away as positioning...
239 my $badspace = pack('U', 0xA0) . "\x{0335}"; # This is at space's pos in OT1
240 $comment =~ s/\Q$badspace\E/ /g;
241 return LaTeXML::Core::Comment->new($comment); }
242 else {
243 return Box(LaTeXML::Package::FontDecodeString($meaning->getString, undef, 1),
244 undef, undef, $meaning); } }
245  
246 # Regurgitate: steal the previously digested boxes from the current level.
247 sub regurgitate {
248 my ($self) = @_;
249 my @stuff = @LaTeXML::LIST;
250 @LaTeXML::LIST = ();
251 return @stuff; }
252  
253 #**********************************************************************
254 # Maintaining State.
255 #**********************************************************************
256 # State changes that the Stomach needs to moderate and know about (?)
257  
258 #======================================================================
259 # Dealing with TeX's bindings & grouping.
260 # Note that lookups happen more often than bgroup/egroup (which open/close frames).
261  
262 sub pushStackFrame {
263 my ($self, $nobox) = @_;
264 $STATE->pushFrame;
265 $STATE->assignValue(beforeAfterGroup => [], 'local'); # ALWAYS bind this!
266 $STATE->assignValue(afterGroup => [], 'local'); # ALWAYS bind this!
267 $STATE->assignValue(afterAssignment => undef, 'local'); # ALWAYS bind this!
268 $STATE->assignValue(groupNonBoxing => $nobox, 'local'); # ALWAYS bind this!
269 $STATE->assignValue(groupInitiator => $LaTeXML::CURRENT_TOKEN, 'local');
270 $STATE->assignValue(groupInitiatorLocator => $self->getLocator, 'local');
271 push(@{ $$self{boxing} }, $LaTeXML::CURRENT_TOKEN) unless $nobox; # For begingroup/endgroup
272 return; }
273  
274 sub popStackFrame {
275 my ($self, $nobox) = @_;
276 if (my $beforeafter = $STATE->lookupValue('beforeAfterGroup')) {
277 if (@$beforeafter) {
278 my @result = map { $_->beDigested($self) } @$beforeafter;
279 if (my ($x) = grep { !$_->isaBox } @result) {
280 Fatal('misdefined', $x, $self, "Expected a Box|List|Whatsit, but got '" . Stringify($x) . "'"); }
281 push(@LaTeXML::LIST, @result); } }
282 my $after = $STATE->lookupValue('afterGroup');
283 $STATE->popFrame;
284 pop(@{ $$self{boxing} }) unless $nobox; # For begingroup/endgroup
285 $$self{gullet}->unread(@$after) if $after;
286 return; }
287  
288 sub currentFrameMessage {
289 my ($self) = @_;
290 return "current frame is "
291 . ($STATE->isValueBound('MODE', 0) # SET mode in CURRENT frame ?
292 ? "mode-switch to " . $STATE->lookupValue('MODE')
293 : ($STATE->lookupValue('groupNonBoxing') # Current frame is a non-boxing group?
294 ? "non-boxing" : "boxing") . " group")
295 . " due to " . Stringify($STATE->lookupValue('groupInitiator'))
296 . " " . ToString($STATE->lookupValue('groupInitiatorLocator')); }
297  
298 #======================================================================
299 # Grouping pushes a new stack frame for binding definitions, etc.
300 #======================================================================
301 # Originally, we only treated math vs text "modes", which are correlated
302 # to grouping (somehow). But we'll gradually need to incorporate all
303 # the horizontal/vertical modes, which are NOT correlated to grouping,
304 # although they do operate on a stack.
305 # So, we should NOT generate errors when the grouping clashes with modes
306 # (until we can get it properly sorted).
307  
308 # if $nobox is true, inhibit incrementing the boxingLevel
309 sub bgroup {
310 my ($self) = @_;
311 pushStackFrame($self, 0);
312 return; }
313  
314 sub egroup {
315 my ($self) = @_;
316 if ( ##$STATE->isValueBound('MODE', 0) || # Last stack frame was a mode switch!?!?!
317 $STATE->lookupValue('groupNonBoxing')) { # or group was opened with \begingroup
318 Error('unexpected', $LaTeXML::CURRENT_TOKEN, $self, "Attempt to close boxing group",
319 $self->currentFrameMessage); }
320 else { # Don't pop if there's an error; maybe we'll recover?
321 popStackFrame($self, 0); }
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/Package.pm ↑ Summary lib/LaTeXML/Global.pm »