1//===- DirectiveNameParser.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Frontend/OpenMP/DirectiveNameParser.h"
10#include "llvm/ADT/Sequence.h"
11#include "llvm/ADT/StringExtras.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/Frontend/OpenMP/OMP.h"
14
15#include <cassert>
16#include <memory>
17
18namespace llvm::omp {
19DirectiveNameParser::DirectiveNameParser(SourceLanguage L) {
20 // Take every directive, get its name in every version, break the name up
21 // into whitespace-separated tokens, and insert each token.
22 for (Directive D : directives()) {
23 if (D == Directive::OMPD_unknown || !(getDirectiveLanguages(D) & L))
24 continue;
25 // Parse "ORDERED" as OMPD_ordered_standalone.
26 if (D == OMPD_ordered_blockassoc)
27 continue;
28 for (unsigned Ver : getOpenMPVersions())
29 insertName(Name: getOpenMPDirectiveName(D, Ver), D);
30 }
31}
32
33const DirectiveNameParser::State *
34DirectiveNameParser::consume(const State *Current, StringRef Tok) const {
35 if (!Current)
36 return Current;
37 assert(Current->isValid() && "Invalid input state");
38 if (const State *Next = Current->next(Tok))
39 return Next->isValid() ? Next : nullptr;
40 return nullptr;
41}
42
43SmallVector<StringRef> DirectiveNameParser::tokenize(StringRef Str) {
44 SmallVector<StringRef> Tokens;
45 SplitString(Source: Str, OutFragments&: Tokens);
46 return Tokens;
47}
48
49void DirectiveNameParser::insertName(StringRef Name, Directive D) {
50 State *Where = &InitialState;
51
52 for (StringRef Tok : tokenize(Str: Name))
53 Where = insertTransition(From: Where, Tok);
54
55 Where->Value = D;
56}
57
58DirectiveNameParser::State *
59DirectiveNameParser::insertTransition(State *From, StringRef Tok) {
60 assert(From && "Expecting state");
61 if (!From->Transition)
62 From->Transition = std::make_unique<State::TransitionMapTy>();
63 if (State *Next = From->next(Tok))
64 return Next;
65
66 auto [Where, DidIt] = From->Transition->try_emplace(Key: Tok, Args: State());
67 assert(DidIt && "Map insertion failed");
68 return &Where->second;
69}
70
71const DirectiveNameParser::State *
72DirectiveNameParser::State::next(StringRef Tok) const {
73 if (!Transition)
74 return nullptr;
75 auto F = Transition->find(Key: Tok);
76 return F != Transition->end() ? &F->second : nullptr;
77}
78
79DirectiveNameParser::State *DirectiveNameParser::State::next(StringRef Tok) {
80 if (!Transition)
81 return nullptr;
82 auto F = Transition->find(Key: Tok);
83 return F != Transition->end() ? &F->second : nullptr;
84}
85} // namespace llvm::omp
86