File: Application.pm

package info (click to toggle)
polymake 4.14-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 35,888 kB
  • sloc: cpp: 168,933; perl: 43,407; javascript: 31,575; ansic: 3,007; java: 2,654; python: 632; sh: 268; xml: 117; makefile: 61
file content (751 lines) | stat: -rw-r--r-- 27,506 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
#  Copyright (c) 1997-2024
#  Ewgenij Gawrilow, Michael Joswig, and the polymake team
#  Technische Universität Berlin, Germany
#  https://polymake.org
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation; either version 2, or (at your option) any
#  later version: http://www.gnu.org/licenses/gpl.txt.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#-------------------------------------------------------------------------------

use strict;
use namespaces;
use warnings qw(FATAL void syntax misc);
use feature 'state';

package Polymake::Core::Application;

declare $configured_at = 2;       # enforce renewal of obsolete config status values=1
declare $load_time = time;

declare $extension;               # Extension contributing to the application being loaded right now
declare $cross_apps_list;         # REQUIRE_APPLICATION active in the current compilation scope

# flags for `load_state' member
use Polymake::Enum LoadState => {
   start => 0,
   namespace_declared => 1,
   main_init_closed => 2,
   cpp_load_initiated => 4,
   credits_shown => 8,
   has_failed_config => 16
};

my (%repository, %configured);

add_settings_callback sub {
   my ($settings) = @_;
   $settings->add_item('_applications::configured', \%configured,
                       "Status and timestamps of rulefile configuration",
                       UserSettings::Item::Flags::by_arch | UserSettings::Item::Flags::hidden,
                       exporter => \&export_configured,
                       importer => \&import_configured);
};

#################################################################################
#
#  Constructor:
#
#  new Application('name', [ rules to load ]);
#
use Polymake::Struct (
   [ new => '$' ],
   [ '$name' => '#1' ],
   [ '$pkg' => '"Polymake::" . #1' ],
   [ '$top' => 'undef' ],         # application top directory (beneath apps/)
   [ '$installTop' => 'undef' ],  # installation directory
   '@myINC',                      # [ directory with perl modules, optional preamble lines ]
   '@scriptpath',                 # directories with scripts
   '@object_types',               # BigObjectType
   '@rules',                      # Rule
   '@rules_to_finalize',          # Rule - production rules defined in the rulefiles being currently read
   '%rulefiles',                  # 'rule_key' => load status
   [ '%configured' => 'undef' ],  # 'rule_key' => configuration result
   '$configured_at',              # last configuration timestamp (2 for core applications unless started with --reconfigure)
   '%rule_code',                  # 'rule_key' => CODE : the complete rulefile-level subroutine
   '%credits',                    # product name => Rule::Credit
   '%credits_by_rulefile',        # 'rule_key' => Rule::Credit
   '%preamble_end',               # 'rule_key' => last line containing a configuration command (CONFIGURE or REQUIRE)
   [ '$prefs' => 'undef' ],       # Preference::perApplication
   [ '$help' => 'new Help(undef, #1)' ],
   '%used',                       # 'name' => Application
   '%imported',                   # 'name' => true
   '@linear_imported',            # [ Application ] flattened list in C3 order
   [ '$compile_scope' => 'undef' ],  # Scope object spanning the load phase of a group of rules
   '$untrusted',                  # TRUE if comes from a writable location, that is, may be under development
   '&eval_expr',                  # eval'uating the given source code in the application-specific lexical context
   [ '$cpp' => 'undef' ],         # CPlusPlus::perAplication
   [ '$load_state' => 'LoadState::start' ],   # flags indicating the rule loading progress
   [ '$default_file_suffix' => 'undef' ],
   '@file_suffixes',
   [ '$origin_extension' => 'undef' ],  # Extension where this application has been introduced
   '@extensions',                 # Extension : extensions contributing to this application (without origin_extension)
);

sub new {
   my $self = &_new;
   if (-d (my $top = "$InstallTop/apps/".$self->name)) {
      if (-f "$top/rules/main.rules") {
         $self->installTop = $InstallTop;
         $self->top = $top;
         $self->configured_at = $configured_at;
         $self->untrusted = $DeveloperMode && -w _;
      } else {
         croak( "Corrupt application ", $self->name, ": missing main.rules file in $top" );
      }
   } else {
      foreach my $ext (@Extension::active[$Extension::num_bundled..$#Extension::active]) {
         if (-d ($top = $ext->app_dir($self))) {
            if (-f "$top/rules/main.rules") {
               $self->installTop = $ext->dir;
               $self->top = $top;
               $self->configured_at = $ext->configured_at;
               $self->untrusted = -w _;
               $self->origin_extension = $ext;
               last;
            } else {
               croak( "Extension ", $ext->dir, " contributes to application ", $self->name,
                      " but does not provide main.rules: missing dependencies and/or wrong order of extensions?" );
            }
         }
      }
      if (!defined($self->top)) {
         croak( "Unknown application ", $self->name );
      }
   }
   RuleFilter::create_self_method_for_application($self);
   {
      no strict 'refs';

      # for quick retrieval in C++ library
      readonly(${$self->pkg."::.APPL"} = $self);

      # prepare an artificial package for proper ordering
      mro::set_mro($self->pkg."::.IMPORTS", "c3");
   }

   my $dir;
   if (-d ($dir = $self->top."/perllib")) {
      push @{$self->myINC}, [ $dir ];
   }
   if (-d ($dir = $self->top."/scripts")) {
      push @{$self->scriptpath}, $dir;
   }

   local $enable_plausibility_checks = $self->untrusted;
   local $Shell = new NoShell();         # disable interactive configuration

   $self->configured = ($configured{$self->name} //= { });
   $self->prefs = $Prefs->app_handler($self);
   $self->cpp = new CPlusPlus::perApplication($self);
   include_rules($self);

   foreach my $ext (@Extension::active) {
      if ($ext->dir ne $self->installTop && -d ($dir = $ext->app_dir($self))) {
         load_extension($self, $ext, $dir);
      }
   }

   $self->cpp->load_private_wrapper;
   $self->prefs->end_loading;

   if ($Help::gather) {
      push @{$self->help->related}, $Help::core;
   }

   $self;
}
#################################################################################
# private:
sub load_extension {
   my ($self, $ext, $app_dir)=@_;
   my $dir;
   if (-d ($dir = "$app_dir/perllib")) {
      push @{$self->myINC}, [ $dir ];
   }
   if (-d ($dir = "$app_dir/scripts")) {
      push @{$self->scriptpath}, $dir;
   }
   local $Extension::loading = $ext;
   local $enable_plausibility_checks = $ext->untrusted;
   include_rules($self);
   push @{$self->extensions}, $ext;
}
#################################################################################
sub add {
   $repository{$_[1]} // do {
      # must access the repository hash twice in order to create the entry before loading the rules:
      # this helps to detect cyclic dependencies
      $repository{$_[1]} //= (my $self=&new);
      SuspendedItems::harvest($self->name);
      $self
   };
}
sub lookup {
   $repository{$_[1]}
}
sub list_loaded {
   values %repository;
}
sub delete {
   delete $repository{$_[1]};
}

sub used_by {
   my ($self) = @_;
   grep { exists($_->used->{$self->name}) } values %repository;
}
#################################################################################
# try to load the application APP
# when an expression APP::FUNCTION(...) is encountered in the user input
sub try_auto_load {
   my ($app_name) = @_;
   my $found;
   namespaces::temp_disable(0);
   if ($app_name =~ /^$id_re$/o && !exists $repository{$app_name}) {
      foreach my $dir ($InstallTop, map { $_->dir } @Extension::active[$Extension::num_bundled .. $#Extension::active]) {
         if (-d "$dir/apps/$app_name") {
            $found = defined( eval { add(__PACKAGE__, $app_name) } );
            last;
         }
      }
   }
   $found
}

#################################################################################
# "rulefile" => ( full_path, extension, rule_key, cached_result_code )
# 'rule_key' is a string used as a key in various maps like rulefiles, configured, or rule_code
sub lookup_rulefile {
   my ($self, $rulename, $only_here) = @_;
   my ($filename, $ext, $rule_key, $rc, @accumulated);
   if (defined($Extension::loading)) {
      # initial loading an extension: first look in the same extension, then in the application root, then in required extensions
      $rule_key = $rulename . '@' . $Extension::loading->URI;
      $filename = $Extension::loading->app_dir($self) . "/rules/$rulename";
      if (defined($rc = $self->rulefiles->{$rule_key}) or -f $filename) {
         if ($only_here < 0) {
            push @accumulated, [ $filename, $Extension::loading, $rule_key, $rc ];
         } else {
            return ($filename, $Extension::loading, $rule_key, $rc);
         }
      }
      unless ($only_here) {
         $filename = $self->top."/rules/$rulename";
         if (defined($rc = $self->rulefiles->{$rulename}) or -f $filename) {
            return ($filename, undef, $rulename, $rc);
         }
         foreach $ext (@{$Extension::loading->requires}) {
            $rule_key = $rulename.'@'.$ext->URI;
            $filename = $ext->app_dir($self) . "/rules/$rulename";
            if (defined($rc = $self->rulefiles->{$rule_key}) or -f $filename) {
               return ($filename, $ext, $rule_key, $rc);
            }
         }
      }

   } elsif ($rulename =~ m{^/}) {
      if (-f $rulename) {
         # catch rules specified by absolute path
         $filename = $rulename;
         ($rulename) = $filename =~ $filename_re;
         if (index($filename, $self->top."/rules/") == 0) {
            return ($filename, undef, $rulename, $self->rulefiles->{$rulename});
         }
         foreach $ext (@{$self->extensions}) {
            if (index($filename, $ext->app_dir($self)."/rules/") == 0) {
               $rule_key = $rulename.'@'.$ext->URI;
               return ($filename, $ext, $rule_key, $self->rulefiles->{$rule_key});
            }
         }
         # stray rulefile without registered extension, presumably user's private experiments
         return ($filename, undef, $filename, $self->rulefiles->{$filename});
      }

   } else {
      # loading on demand: first look in the application root, then in all extensions
      $filename = $self->top."/rules/$rulename";
      if (defined($rc = $self->rulefiles->{$rulename}) or -f $filename) {
         if ($only_here < 0) {
            push @accumulated, [ $filename, undef, $rulename, $rc ];
         } else {
            return ($filename, undef, $rulename, $rc);
         }
      }
      foreach $ext (@{$self->extensions}) {
         $filename = $ext->app_dir($self)."/rules/$rulename";
         $rule_key = $rulename.'@'.$ext->URI;
         if (defined($rc = $self->rulefiles->{$rule_key}) or -f $filename) {
            if ($only_here < 0) {
               push @accumulated, [ $filename, $ext, $rule_key, $rc ];
            } else {
               return ($filename, $ext, $rule_key, $rc);
            }
         }
      }
   }

   @accumulated
}
#################################################################################
sub exclude_rule {
   my ($self, $rulename)=@_;
   if ($rulename =~ /^($id_re)::(.*)/o) {
      exclude_rule($self->used->{$1} || croak( "application $1 is not declared as USE'd or IMPORT'ed - may not load its rules here" ), "$2");
   } else {
      if (my ($filename, $ext, $rule_key) = lookup_rulefile($self, $rulename)) {
         # don't exclude if already loaded from elsewhere
         if (!exists $self->rulefiles->{$rule_key}) {
            $self->rulefiles->{$rule_key} = 0;
            delete $self->configured->{$rule_key};
         }
      } else {
         croak( "rule file ", $self->name, "::$rulename does not exist" );
      }
   }
}
#################################################################################
# private
sub include_rule {
   my ($self, $rulefile, $only_here) = @_;
   if ($rulefile =~ m{^($id_re)::(.*)}o) {
      include_rules($self->used->{$1} || croak( "application $1 is not declared as USE'd or IMPORT'ed - may not load its rules here" ), "$2");
   } elsif ($rulefile =~ s{^\*/(.*)}{$1}) {
      my $rc_all = 0;
      foreach my $app (reverse(@{$self->linear_imported}),
                       (grep { !$self->imported->{$_->name} } values %{$self->used}), $self) {
         if (my @found = lookup_rulefile($app, $rulefile, -1)) {
            if ($app == $self) {
               foreach (@found) {
                  $rc_all += process_included_rule($app, $rulefile, @$_);
               }
            } else {
               $rc_all += include_rules($app, $rulefile, @found);
            }
         }
      }
      $rc_all;
   } elsif (my @found = &lookup_rulefile) {
      process_included_rule($self, $rulefile, @found);
   } else {
      $only_here || croak( "rule file ", ($rulefile =~ m{^/} ? $rulefile : $self->name."::$rulefile"), " does not exist" );
   }
}
#################################################################################
sub include_rules {
   my $self = shift;
   local if (is_code($INC[0])) {
      if ($User::application != $self) {
         local unshift @INC, $self;
      }
   } elsif (is_object($INC[0])) {
      if ($INC[0] != $self) {
         local $INC[0] = $self;
      }
   } else {
      local unshift @INC, $self;
   }
   local scalar $self->compile_scope = new Scope();
   my $rc_all=0;
   eval {
      if (@_) {
         # application is already loaded, adding some optional rulefiles
         if (is_array($_[-1])) {
            # recursive call from include_rule with a wildcard application
            my $rulefile = shift;
            foreach my $found (@_) {
               $rc_all += process_included_rule($self, $rulefile, @$found);
            }
         } else {
            foreach my $rulefile (@_) {
               $rc_all += include_rule($self, $rulefile);
            }
         }
      } else {
         # initializing the application or its main part in an extension
         local $CPlusPlus::code_generation = "" if $CPlusPlus::code_generation eq "private";
         $self->load_state &= ~LoadState::cpp_load_initiated;
         if ($rc_all = include_rule($self, "main.rules", 1)) {
            unless ($self->load_state & LoadState::cpp_load_initiated) {
               # no rulefiles at all; nevertheless, there might be clients
               $self->load_state |= LoadState::cpp_load_initiated;
               $self->cpp->start_loading($Extension::loading);
            }
            $self->cpp->end_loading($Extension::loading);
         }
      }
      $_->finalize for @{$self->rules_to_finalize};
   };
   if ($@) {
      die beautify_error();
   }
   @{$self->rules_to_finalize} = ();
   $rc_all;
}
#################################################################################
sub include_rule_block {
   my ($self, $mandatory, $block)=@_;
   while ($block =~ /\G \s* (\S+)/gx) {
      my @failed;
      my $rulefile = $1;
      my $success = include_rule($self, $rulefile);
      if ($mandatory) {
         push @failed, $rulefile if !$success;
      } else {
         while ($block =~ /\G \s+\+\s+ (\S+)/gxc) {
            $rulefile = $1;
            $success += include_rule($self, $rulefile);
         }
      }
      while ($block =~ /\G \s+\|\s+ (\S+)/gxc) {
         $rulefile = $1;
         if ($success) {
            exclude_rule($self, $rulefile) if !$mandatory;
         } else {
            $success = include_rule($self, $rulefile);
            push @failed, $rulefile if $success < $mandatory;
         }
      }
      return @failed if $success < $mandatory;
   }
   ()
}
#################################################################################
sub eval_type {
   my ($self, $expr, $allow_generic)=@_;
   $self->eval_expr->($allow_generic && $expr !~ /[<>]/ ? "typeof_gen $expr" : "typeof $expr")
}

# called from C++ library
sub construct_type {
   my ($self, $typename) = splice @_, 0, 2;
   local @ARGV = @_ and my $params='(@ARGV)';
   $self->eval_expr->("typeof $typename$params")
     // croak( $@ =~ /^invalid type expression/ ? "$& $typename" : "Error processing type expression $typename: $@" );
}

# called from C++ library
sub construct_explicit_typelist {
   my $self = shift;
   $self->eval_expr->("bless [" . join(",", map { "typeof $_" } @_) . "], 'namespaces::ExplicitTypelist'")
     // croak( $@ =~ /^invalid type expression/ ? "$& @_" : "Error processing type expressions @_: $@" );
}
#################################################################################
sub set_file_suffix {
   my ($self, $suffix) = @_;
   ($self->default_file_suffix &&= croak("multiple definition of default file suffix")) ||= $suffix;
   push @{$self->file_suffixes}, $suffix;
}
#################################################################################
sub lookup_credit {
   my ($self, $product) = @_;
   $self->credits->{$product} //= do {
      my $credit;
      foreach my $app (values %{$self->used}) {
         if (defined($credit = $app->credits->{$product})) {
            keys %{$self->used};
            last;
         }
      }
      $credit
   };
}
#################################################################################
sub use_apps {
   my ($self, $import) = splice @_, 0, 2;
   my ($i, $app);

   my $in_ext = $Extension::loading;
   local $Extension::loading;

   my @apps = map {
      if (my ($appname, $start_rules) = m/^\s* ($id_re) (?: \s*\(\s* (.*?) \s*\) )? \s*$/xo) {
         if (exists $repository{$appname} && !defined $repository{$appname}) {
            # requested application is itself being loaded
            croak( "Cyclic dependence between applications ", $self->name, " and $appname" );
         }
         $app = add Application($appname);
         if (exists $app->used->{$self->name}) {
            if ($in_ext) {
               croak( "Extension ", $in_ext->URI,
                      " attempts to introduce a cyclic dependence between applications ", $self->name, " and $appname" );
            } else {
               croak( "Cyclic dependence between applications ", $self->name, " and $appname" );
            }
         }
         if (defined($start_rules) &&
             scalar(include_rule_block($app, 1, $start_rules))) {
            croak( "could not load mandatory rulefile(s) $start_rules due to configuration issues" );
         }
         $app
      } else {
         croak( "invalid application name '$_'" );
      }
   } @_;

   if ($import) {
      {  no strict 'refs';
         push @{$self->pkg."::.IMPORTS::ISA"}, map { $_->pkg."::.IMPORTS" } @apps;
         my $linear_isa = mro::get_linear_isa($self->pkg."::.IMPORTS");
         @{$self->linear_imported} = map { ${s/IMPORTS$/APPL/r} } @$linear_isa[1..$#$linear_isa];
      }
      foreach my $app (@{$self->linear_imported}) {
         push @{$self->myINC}, @{$app->myINC};
         push %{$self->credits}, %{$app->credits};
         namespaces::using($self->pkg, $app->pkg);
         $self->imported->{$app->name} = true;
         push @{$self->prefs->imported}, $app->prefs;
         push @{$self->help->related}, $app->help if $Help::gather;
      }
   }

   foreach my $app (@apps) {
      $self->used->{$_->name} = $_ for $app, values %{$app->used};
   }
}

sub common {
   my ($self, $other)=@_;
   if (!defined($other) || $self == $other || exists $self->used->{$other->name}) {
      $self;
   } elsif (exists $other->used->{$self->name}) {
      $other;
   } else {
      undef;
   }
}

#################################################################################
sub get_custom_item {
   my ($self, $name) = @_;
   $name =~ s/^[\$\@%]//;
   if ($name =~ /^($id_re)::/o) {
      if (defined(my $app = $repository{$1})) {
         $name = $';
         $self = $app;
      } elsif ($1 eq "User") {
         $name = "Polymake::$name";
      }
   }
   $Settings->items->{$name} // $name !~ /::/ && do {
      foreach my $app ($self, values %{$self->used}) {
         if (defined(my $item = $Settings->items->{$app->pkg . "::$name"})) {
            keys %{$self->used};
            return $item;
         }
      }
      croak( "unknown custom variable $name" );
   };
}

# for clients and callable library:

# Application, 'varname', [key] => value
sub get_custom_var {
   my $item = &get_custom_item;
   if (@_ > 2) {
      if (is_hash($item->ref)) {
         $item->ref->{$_[2]}
      } else {
         die "key specified with a non-hash custom variable $_[1]\n"
      }
   } else {
      is_scalar_ref($item->ref) ? ${$item->ref} : $item->ref
   }
}
#################################################################################
sub import_configured {
   my ($value) = @_;
   if (keys %configured) {
      while (my ($appname, $statuses) = each %$value) {
         push %{$configured{$appname} //= { }}, %$statuses;
      }
   } else {
      push %configured, %$value;
   }
}

# only export fully configured rulefiles
sub export_configured {
   my ($include_imported, $imported_config) = @_;
   my %export;
   $include_imported ||= !is_hash($imported_config);
   while (my ($appname, $value) = each %configured) {
      my $imported_app = !$include_imported && $imported_config->{$appname};
      my %rulefiles = map {
         my $status = $value->{$_};
         $status =~ /^[1-9]\d+$/ && !(is_hash($imported_app) && $value eq $imported_app->{$_})
         ? ($_ => $status) : ()
      } keys %$value;
      if (keys %rulefiles) {
         $export{$appname} = \%rulefiles;
      }
   }
   keys %export ? \%export : ()
}
#################################################################################
sub add_top_label {
   my ($self, $name) = @_;
   my $label = ( $self->prefs->labels->{$name} &&=
                 croak( "multiple definition of label $name" ) ) = new Preference::Label($name);
   $label->application = $self;
   $label->extension = $Extension::loading;
   $label
}

sub add_label {
   my ($self, $name) = @_;
   my $label = $self->prefs->find_label($name, 1) or do {
      $name =~ /^($id_re)/o;
      croak( "unknown label '$1'" );
   };
   $label->set_application($self, $Extension::loading);
   $label
}
#################################################################################
sub prefer {
   my ($self, $expr) = @_;
   $self->prefs->add_preference($expr, Preference::Mode::strict);
}

sub prefer_now {
   my ($self, $expr) = @_;
   $self->prefs->set_temp_preference($Scope, $expr);
}

# an alias, for the sake of symmetry
*set_preference=\&prefer;

sub reset_preference {
   my $self = shift;
   if ($_[0] eq "all" || $_[0] eq "*") {
      $Prefs->reset_all($self);
   } else {
      $Prefs->reset($self, @_);
   }
}
#################################################################################
sub find_rule_label {
   my ($self, $pattern) = @_;
   $self->prefs->find_label($pattern)
}

sub all_production_rules {
   my ($self) = @_;
   grep { $_->flags & Rule::Flags::is_production } @{$self->rules}
}

*find_rules_by_pattern = \&Rule::find_by_pattern;
*disable_rules = \&BigObjectType::disable_rules;

#################################################################################
# This is a placeholder with minimal functionality required for RuleFilter to load
# scripts and data upgrade rules in an early stage, when no real application
# is loaded yet.
sub load_dummy {
   $User::application = _new(__PACKAGE__, "");
   $User::application->configured = { };
   push @INC, $User::application;
   readonly($User::application);
}
#################################################################################
package Polymake::Core::Application::SuspendedItems;

use Polymake::Struct (
   [ new => '$$@' ],
   [ '$application' => '#1' ],
   [ '$extension' => '#2' ],
   [ '@further_missing_apps' => '@' ],
   '@rulefiles',
   '@rule_keys',
   '@embedded_rules',
   '@functions',
);

my %suspended;

sub add {
   my ($application, $extension, $missing_app_name, @further_missing_apps) = @_;
   my $list = ($suspended{$missing_app_name} //= [ ]);
   my $self;
   # Only look at the end of the list and stop by first application or extension mismatch,
   # because all suspended items are created at the same time, when the owning application is loaded.
   for (my $i = $#$list; $i >= 0; --$i) {
      $self = $list->[$i];
      if ($self->application == $application && $self->extension == $extension) {
         if (equal_lists($self->further_missing_apps, \@further_missing_apps)) {
            return $self;
         }
      } else {
         last;
      }
   }
   $self = new(__PACKAGE__, $application, $extension, @further_missing_apps);
   push @$list, $self;
   $self
}

sub harvest {
   my ($app_name) = @_;

   if (defined(my $list = delete $suspended{$app_name})) {
      foreach my $self (@$list) {
         if (my @missing_apps = grep { !exists $repository{$_} } @{$self->further_missing_apps}) {
            # Associate the suspended items with another missing application.
            my $missing_app_name = shift @missing_apps;
            my $next_list = ($suspended{$missing_app_name} //= [ ]);
            # Look though the entire list, because anything might have happened since the initial load of the owning application.
            foreach my $next_suspended (@$next_list) {
               if ($next_suspended->application == $self->application &&
                   $next_suspended->extension == $self->extension &&
                   equal_lists($next_suspended->further_missing_apps, \@missing_apps)) {

                  push @{$next_suspended->rulefiles}, @{$self->rulefiles};
                  push @{$next_suspended->rule_keys}, @{$self->rule_keys};
                  push @{$next_suspended->embedded_rules}, @{$self->embedded_rules};
                  push @{$next_suspended->functions}, @{$self->functions};
                  undef $self;
                  last;
               }
            }
            if ($self) {
               @{$self->further_missing_apps}=@missing_apps;
               push @$next_list, $self;
            }
         } else {
            # ripe to be loaded
            my $app = $self->application;
            local $Extension::loading = $self->extension;
            local unshift @INC, $app;
            local scalar $app->compile_scope = new Scope();
            eval {
               local $CPlusPlus::code_generation = "" if $CPlusPlus::code_generation eq "private";
               if (@{$self->rulefiles}) {
                  delete @{$app->rulefiles}{@{$self->rule_keys}};
                  delete @INC{ map { "rules:$_" } @{$self->rulefiles} };
                  foreach my $rulefile (@{$self->rulefiles}) {
                     include_rule($app, $rulefile);
                  }
               }
               $self->application->cpp->load_suspended($self);
            };
            if ($@) {
               die beautify_error();
            }
         }
      }
   }
}

1

# Local Variables:
# cperl-indent-level:3
# indent-tabs-mode:nil
# End: