summaryrefslogtreecommitdiffstats
path: root/source/core/slang-command-options-writer.cpp
blob: 308cc4984dc47af00885ffd31314b29bd6f2bcb0 (plain)
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
// slang-command-options-writer.cpp

#include "slang-command-options-writer.h"

#include "slang-byte-encode-util.h"
#include "slang-char-util.h"
#include "slang-string-util.h"

namespace Slang
{

namespace
{ // anonymous
typedef CommandOptionsWriter::Style Style;
} // namespace

static bool _isMarkdown(Style style)
{
    return style == Style::Markdown || style == Style::NoLinkMarkdown;
}
static bool _hasLinks(Style style)
{
    return style == Style::Markdown;
}

/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! MarkdownCommandOptionsWriter !!!!!!!!!!!!!!!!!!!!!!!!!!! */

class MarkdownCommandOptionsWriter : public CommandOptionsWriter
{
public:
    typedef CommandOptionsWriter Super;

    typedef uint32_t LinkFlags;
    struct LinkFlag
    {
        enum Enum
        {
            Category = 0x1,
            Option = 0x2,

            All = Category | Option,
        };
    };

    MarkdownCommandOptionsWriter(const Options& options)
        : Super(options)
    {
    }

protected:
    // CommandOptionsWriter
    virtual void appendDescriptionForCategoryImpl(Index categoryIndex) SLANG_OVERRIDE;
    virtual void appendDescriptionImpl() SLANG_OVERRIDE;

    void _appendParagraph(const UnownedStringSlice& text, LinkFlags flags = LinkFlag::All);
    void _appendParagraph(
        const ConstArrayView<UnownedStringSlice>& words,
        LinkFlags flags = LinkFlag::All);

    void _appendMaybeLink(const UnownedStringSlice& word, LinkFlags linkFlags);

    void _appendText(const UnownedStringSlice& text);
    void _appendDescriptionForCategory(Index categoryIndex);
    UnownedStringSlice _getLinkName(CommandOptions::LookupKind kind, Index index);
    UnownedStringSlice _getLinkName(const NameKey& key, Index index);

    void _appendQuickLinks();

    bool m_hasLinks = false;
    Dictionary<NameKey, StringSlicePool::Handle> m_linkMap;
};

void MarkdownCommandOptionsWriter::appendDescriptionForCategoryImpl(Index categoryIndex)
{
    // No point doing links for a single category
    m_hasLinks = false;
    _appendDescriptionForCategory(categoryIndex);
}


void MarkdownCommandOptionsWriter::appendDescriptionImpl()
{
    m_hasLinks = _hasLinks(m_options.style);

    if (m_hasLinks)
    {
        _appendQuickLinks();
    }

    // Go through categories in order
    const auto& categories = m_commandOptions->getCategories();
    for (Index categoryIndex = 0; categoryIndex < categories.getCount(); ++categoryIndex)
    {
        _appendDescriptionForCategory(categoryIndex);
    }
}

static bool _needsMarkdownEscape(const UnownedStringSlice& text)
{
    for (auto c : text)
    {
        switch (c)
        {
        case '<':
        case '>':
        case '&':
        case '[':
        case ']':
            {
                return true;
            }
        default:
            break;
        }
    }

    return false;
}

void _appendEscapedMarkdown(const UnownedStringSlice& text, StringBuilder& ioBuf)
{
    if (_needsMarkdownEscape(text))
    {
        // Replace any < > &
        for (auto c : text)
        {
            switch (c)
            {
            case '<':
                ioBuf << "&lt;";
                break;
            case '>':
                ioBuf << "&gt;";
                break;
            case '&':
                ioBuf << "&amp;";
                break;
            case '[':
                ioBuf << "\\[";
                break;
            case ']':
                ioBuf << "\\]";
                break;
            default:
                ioBuf << c;
            }
        }
    }
    else
    {
        ioBuf << text;
    }
}

void MarkdownCommandOptionsWriter::_appendQuickLinks()
{
    const auto& categories = m_commandOptions->getCategories();
    const auto count = categories.getCount();

    m_builder << "### Quick Links\n\n";

    for (Index categoryIndex = 0; categoryIndex < count; ++categoryIndex)
    {
        const auto& cat = categories[categoryIndex];

        m_builder << "* [";
        _appendEscapedMarkdown(cat.name, m_builder);
        m_builder << "](#" << _getLinkName(LookupKind::Category, categoryIndex) << ")\n";
    }

    m_builder << "\n";
}

void MarkdownCommandOptionsWriter::_appendParagraph(
    const UnownedStringSlice& text,
    LinkFlags linkFlags)
{
    List<UnownedStringSlice> words;
    StringUtil::splitOnWhitespace(text, words);
    _appendParagraph(words.getArrayView(), linkFlags);
}

static bool _isEndPunctionation(char c)
{
    return c == '.' || c == ')' || c == ',';
}

static bool _isStartPunctionation(char c)
{
    return c == '(' || c == ',';
}

static UnownedStringSlice _trimPunctuation(const UnownedStringSlice& word)
{
    const char* start = word.begin();
    const char* end = word.end();

    while (start < end && _isStartPunctionation(*start))
        start++;
    while (end > start && _isEndPunctionation(end[-1]))
        --end;
    return UnownedStringSlice(start, end);
}

void MarkdownCommandOptionsWriter::_appendMaybeLink(
    const UnownedStringSlice& inWord,
    LinkFlags linkFlags)
{
    if (linkFlags)
    {
        auto trimmedWord = _trimPunctuation(inWord);

        if (trimmedWord.getLength())
        {
            Index index = -1;
            NameKey nameKey;

            // Look for options
            if (trimmedWord[0] == '-' && (linkFlags & LinkFlag::Option))
            {
                index = m_commandOptions->findTargetIndexByName(
                    LookupKind::Option,
                    trimmedWord,
                    &nameKey);
            }
            else if (
                trimmedWord[0] == '<' && trimmedWord[trimmedWord.getLength() - 1] == '>' &&
                (linkFlags & LinkFlag::Category))
            {
                index = m_commandOptions->findTargetIndexByName(
                    LookupKind::Category,
                    trimmedWord.subString(1, trimmedWord.getLength() - 2),
                    &nameKey);
            }

            if (index > 0)
            {
                // Append before the link
                _appendEscapedMarkdown(
                    UnownedStringSlice(inWord.begin(), trimmedWord.begin()),
                    m_builder);

                // Make into a link
                m_builder << "[";
                _appendEscapedMarkdown(trimmedWord, m_builder);
                m_builder << "](#" << _getLinkName(nameKey, index) << ")";

                // Append after the link
                _appendEscapedMarkdown(
                    UnownedStringSlice(trimmedWord.end(), inWord.end()),
                    m_builder);
                return;
            }
        }
    }

    _appendEscapedMarkdown(inWord, m_builder);
}

void MarkdownCommandOptionsWriter::_appendParagraph(
    const ConstArrayView<UnownedStringSlice>& words,
    LinkFlags linkFlags)
{
    if (m_hasLinks && linkFlags)
    {
        for (auto word : words)
        {
            _appendMaybeLink(word, linkFlags);
            m_builder << " ";
        }
    }
    else
    {
        for (auto word : words)
        {
            _appendEscapedMarkdown(word, m_builder);
            m_builder << " ";
        }
    }
}

void MarkdownCommandOptionsWriter::_appendText(const UnownedStringSlice& text)
{
    List<UnownedStringSlice> lines;
    StringUtil::calcLines(text, lines);
    for (auto line : lines)
    {
        if (line.startsWith(toSlice(" ")))
        {
            // If prefixed means we want to display as is
            m_builder << "> " << line << "\n";
        }
        else
        {
            _appendParagraph(line);
            m_builder << "\n\n";
        }
    }
}


void MarkdownCommandOptionsWriter::_appendDescriptionForCategory(Index categoryIndex)
{
    auto& options = *m_commandOptions;

    const auto& categories = options.getCategories();
    const auto& category = categories[categoryIndex];

    const bool isValue = (category.kind == CommandOptions::CategoryKind::Value);

    // Header
    {
        if (m_hasLinks)
        {
            // Output anchor
            m_builder << "<a id=\"" << _getLinkName(LookupKind::Category, categoryIndex)
                      << "\"></a>\n";
        }

        m_builder << "## " << category.name << "\n\n";

        // If there is a description output, making \n split paragraphs
        if (category.description.getLength() > 0)
        {
            _appendText(category.description);
        }
    }

    for (Index optionIndex = category.optionStartIndex; optionIndex < category.optionEndIndex;
         ++optionIndex)
    {
        const auto& option = options.getOptionAt(optionIndex);

        {
            List<UnownedStringSlice> names;
            StringUtil::split(option.names, ',', names);

            if (isValue)
            {
                m_builder << "* ";
                // Output all the names
                m_builder << "`";
                StringUtil::join(names.getBuffer(), names.getCount(), toSlice("`, `"), m_builder);
                m_builder << "` ";
            }
            else
            {
                if (m_hasLinks)
                {
                    m_builder << "<a id=\"" << _getLinkName(LookupKind::Option, optionIndex)
                              << "\"></a>\n";
                }

                m_builder << "### ";
                StringUtil::join(names.getBuffer(), names.getCount(), toSlice(", "), m_builder);
                m_builder << "\n";

                if (option.usage.getLength())
                {
                    m_builder << "\n**";

                    if (m_hasLinks)
                    {
                        List<UnownedStringSlice> usedCategories;
                        options.splitUsage(option.usage, usedCategories);

                        const char* cur = option.usage.begin();
                        for (auto usedCategory : usedCategories)
                        {
                            _appendEscapedMarkdown(
                                UnownedStringSlice(cur, usedCategory.begin()),
                                m_builder);

                            // Now do the link
                            const Index usedCategoryIndex =
                                options.findCategoryByName(usedCategory);

                            m_builder << "[" << usedCategory << "](#"
                                      << _getLinkName(LookupKind::Category, usedCategoryIndex)
                                      << ")";

                            cur = usedCategory.end();
                        }

                        _appendEscapedMarkdown(
                            UnownedStringSlice(cur, option.usage.end()),
                            m_builder);
                    }
                    else
                    {
                        _appendEscapedMarkdown(option.usage, m_builder);
                    }

                    m_builder << "**\n\n";
                }
            }
        }

        if (option.description.getLength() > 0)
        {
            if (isValue)
            {
                m_builder << ": ";
                _appendParagraph(option.description);
            }
            else
            {
                _appendText(option.description);
            }
        }

        m_builder << "\n";
    }

    m_builder << "\n";
}

UnownedStringSlice MarkdownCommandOptionsWriter::_getLinkName(const NameKey& key, Index index)
{
    if (auto ptr = m_linkMap.tryGetValue(key))
    {
        return m_pool.getSlice(*ptr);
    }

    UnownedStringSlice prefix = (key.kind == CommandOptions::LookupKind::Category)
                                    ? m_commandOptions->getFirstNameForCategory(index)
                                    : m_commandOptions->getFirstNameForOption(index);
    prefix = prefix.trim('-');

    if (prefix.getLength() == 0)
    {
        prefix = toSlice("id");
    }

    StringBuilder buf;
    buf << prefix;

    const auto bufLen = buf.getLength();

    for (Index i = 0; i < 1000; ++i)
    {
        buf.reduceLength(bufLen);

        if (i > 0)
        {
            buf << "-" << i;
        }

        if (!m_pool.has(buf.getUnownedSlice()))
        {
            break;
        }
    }

    const auto handle = m_pool.add(buf.getUnownedSlice());
    m_linkMap.add(key, handle);

    return m_pool.getSlice(handle);
}

UnownedStringSlice MarkdownCommandOptionsWriter::_getLinkName(
    CommandOptions::LookupKind kind,
    Index index)
{
    auto& options = *m_commandOptions;

    // Set up the name key
    const auto key = (kind == LookupKind::Category) ? options.getNameKeyForCategory(index)
                                                    : options.getNameKeyForOption(index);

    return _getLinkName(key, index);
}

/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! TextCommandOptionsWriter !!!!!!!!!!!!!!!!!!!!!!!!!!! */

class TextCommandOptionsWriter : public CommandOptionsWriter
{
public:
    typedef CommandOptionsWriter Super;

    TextCommandOptionsWriter(const Options& options)
        : Super(options)
    {
    }

protected:
    // CommandOptionsWriter
    virtual void appendDescriptionForCategoryImpl(Index categoryIndex) SLANG_OVERRIDE;
    virtual void appendDescriptionImpl() SLANG_OVERRIDE;

    void _appendText(Count indentCount, const UnownedStringSlice& text);
    void _appendDescriptionForCategory(Index categoryIndex);
};

void TextCommandOptionsWriter::appendDescriptionForCategoryImpl(Index categoryIndex)
{
    _appendDescriptionForCategory(categoryIndex);
}

void TextCommandOptionsWriter::appendDescriptionImpl()
{
    const auto& categories = m_commandOptions->getCategories();
    for (Index categoryIndex = 0; categoryIndex < categories.getCount(); ++categoryIndex)
    {
        _appendDescriptionForCategory(categoryIndex);
    }
}

void TextCommandOptionsWriter::_appendDescriptionForCategory(Index categoryIndex)
{
    auto& options = *m_commandOptions;

    const auto& categories = options.getCategories();
    const auto& category = categories[categoryIndex];

    // Header
    {
        const auto count = m_builder.getLength();
        if (category.kind == CategoryKind::Value)
        {
            m_builder << "<" << category.name << ">";
        }
        else
        {
            m_builder << category.name;
        }

        const auto length = m_builder.getLength() - count;
        m_builder << "\n";

        m_builder.appendRepeatedChar('=', length);

        m_builder << "\n\n";

        // If there is a description output it
        if (category.description.getLength() > 0)
        {
            _appendText(0, category.description);
            m_builder << "\n";
        }
    }

    for (auto& option : options.getOptionsForCategory(categoryIndex))
    {
        m_builder << m_options.indent;

        if (option.usage.getLength())
        {
            m_builder << option.usage;
        }
        else
        {
            List<UnownedStringSlice> names;
            StringUtil::split(option.names, ',', names);

            _appendWrappedIndented(1, names, toSlice(", "));
        }

        if (option.description.getLength() == 0)
        {
            m_builder << "\n";
            continue;
        }

        m_builder << ": ";

        _appendText(2, option.description);

        if (option.usage.getLength())
        {
            List<Index> usageCategoryIndices;
            options.findCategoryIndicesFromUsage(option.usage, usageCategoryIndices);

            for (auto usageCategoryIndex : usageCategoryIndices)
            {
                auto& usageCat = categories[usageCategoryIndex];

                m_builder << m_options.indent << m_options.indent;

                m_builder << "<" << usageCat.name << "> can be: ";

                List<UnownedStringSlice> optionNames;
                options.getCategoryOptionNames(usageCategoryIndex, optionNames);

                _appendWrappedIndented(2, optionNames, toSlice(", "));

                m_builder << "\n";
            }
        }
    }

    m_builder << "\n";
}

void TextCommandOptionsWriter::_appendText(Count indentCount, const UnownedStringSlice& text)
{
    List<UnownedStringSlice> lines;
    StringUtil::calcLines(text, lines);

    // Remove very last line if it's empty
    if (lines.getCount() > 1 && lines.getLast().trim().getLength() == 0)
    {
        lines.removeLast();
    }

    List<UnownedStringSlice> words;

    for (auto line : lines)
    {
        if (line.startsWith(toSlice(" ")))
        {
            // Append the line as is after the indent
            _requireIndent(indentCount);
            m_builder << line;
        }
        else if (line.trim().getLength() == 0)
        {
        }
        else
        {
            words.clear();
            StringUtil::split(line, ' ', words);

            _requireIndent(indentCount);
            _appendWrappedIndented(indentCount, words, toSlice(" "));
        }

        m_builder << "\n";
    }
}

/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! CommandOptionsWriter !!!!!!!!!!!!!!!!!!!!!!!!!!! */

typedef CommandOptionsWriter::Style Style;

static const NamesDescriptionValue s_styleInfos[] = {
    {ValueInt(Style::Text), "text", "Text suitable for output to a terminal"},
    {ValueInt(Style::Markdown), "markdown", "Markdown"},
    {ValueInt(Style::NoLinkMarkdown), "no-link-markdown", "Markdown without links"},
};

/* static */ ConstArrayView<NamesDescriptionValue> CommandOptionsWriter::getStyleInfos()
{
    return makeConstArrayView(s_styleInfos);
}

CommandOptionsWriter::CommandOptionsWriter(const Options& options)
    : m_pool(StringSlicePool::Style::Default), m_options(options)
{
    m_options.indent = m_pool.addAndGetSlice(options.indent);
}

/* static */ RefPtr<CommandOptionsWriter> CommandOptionsWriter::create(const Options& options)
{
    if (_isMarkdown(options.style))
    {
        return new MarkdownCommandOptionsWriter(options);
    }
    else
    {
        return new TextCommandOptionsWriter(options);
    }
}

void CommandOptionsWriter::appendDescriptionForCategory(
    CommandOptions* options,
    Index categoryIndex)
{
    m_commandOptions = options;
    appendDescriptionForCategoryImpl(categoryIndex);
    m_commandOptions = nullptr;
}

void CommandOptionsWriter::appendDescription(CommandOptions* options)
{
    m_commandOptions = options;
    appendDescriptionImpl();
    m_commandOptions = nullptr;
}

Count CommandOptionsWriter::_getCurrentLineLength()
{
    // Work out the current line length
    const char* start = m_builder.begin();
    const char* cur = m_builder.end();

    Count lineLength = 0;

    if (cur > start)
    {
        for (--cur; cur > start; --cur)
        {
            const auto c = *cur;
            if (c == '\n' || c == '\r')
            {
                ++cur;
                break;
            }
        }

        lineLength = Count(ptrdiff_t(m_builder.end() - cur));
    }

    return lineLength;
}

void CommandOptionsWriter::_requireIndent(Count indentCount)
{
    const auto length = m_builder.getLength();
    if (length)
    {
        const auto c = m_builder[length - 1];
        if (c == '\n' || c == '\r')
        {
            for (Index j = 0; j < indentCount; j++)
            {
                m_builder.append(m_options.indent);
            }
        }
    }
}

void CommandOptionsWriter::_appendWrappedIndented(
    Count indentCount,
    List<UnownedStringSlice>& slices,
    const UnownedStringSlice& delimit)
{
    Count lineLength = _getCurrentLineLength();

    const auto count = slices.getCount();

    for (Index i = 0; i < count; ++i)
    {
        auto slice = slices[i];

        auto sliceLength = slice.getLength();

        if (i < count - 1)
        {
            sliceLength += delimit.getLength();
        }

        // If out of space onto the next line
        if (lineLength + sliceLength > m_options.lineLength)
        {
            m_builder.append("\n");

            lineLength = indentCount * m_options.indent.getLength();

            for (Index j = 0; j < indentCount; j++)
            {
                m_builder.append(m_options.indent);
            }
        }

        m_builder.append(slice);
        if (i < count - 1)
        {
            m_builder.append(delimit);
        }

        lineLength += sliceLength;
    }
}

} // namespace Slang