1 //===-- lib/Parser/Fortran-parsers.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 // Top-level grammar specification for Fortran. These parsers drive 10 // the tokenization parsers in cooked-tokens.h to consume characters, 11 // recognize the productions of Fortran, and to construct a parse tree. 12 // See ParserCombinators.md for documentation on the parser combinator 13 // library used here to implement an LL recursive descent recognizer. 14 15 // The productions that follow are derived from the draft Fortran 2018 16 // standard, with some necessary modifications to remove left recursion 17 // and some generalization in order to defer cases where parses depend 18 // on the definitions of symbols. The "Rxxx" numbers that appear in 19 // comments refer to these numbered requirements in the Fortran standard. 20 21 // The whole Fortran grammar originally constituted one header file, 22 // but that turned out to require more memory to compile with current 23 // C++ compilers than some people were willing to accept, so now the 24 // various per-type parsers are partitioned into several C++ source 25 // files. This file contains parsers for constants, types, declarations, 26 // and misfits (mostly clauses 7, 8, & 9 of Fortran 2018). The others: 27 // executable-parsers.cpp Executable statements 28 // expr-parsers.cpp Expressions 29 // io-parsers.cpp I/O statements and FORMAT 30 // openmp-parsers.cpp OpenMP directives 31 // program-parsers.cpp Program units 32 33 #include "basic-parsers.h" 34 #include "expr-parsers.h" 35 #include "misc-parsers.h" 36 #include "stmt-parser.h" 37 #include "token-parsers.h" 38 #include "type-parser-implementation.h" 39 #include "flang/Parser/parse-tree.h" 40 #include "flang/Parser/user-state.h" 41 42 namespace Fortran::parser { 43 44 // R601 alphanumeric-character -> letter | digit | underscore 45 // R603 name -> letter [alphanumeric-character]... 46 constexpr auto nonDigitIdChar{letter || otherIdChar}; 47 constexpr auto rawName{nonDigitIdChar >> many(nonDigitIdChar || digit)}; 48 TYPE_PARSER(space >> sourced(rawName >> construct<Name>())) 49 50 // R604 constant -> literal-constant | named-constant 51 // Used only via R607 int-constant and R845 data-stmt-constant. 52 // The look-ahead check prevents occlusion of constant-subobject in 53 // data-stmt-constant. 54 TYPE_PARSER(construct<ConstantValue>(literalConstant) || 55 construct<ConstantValue>(namedConstant / !"%"_tok / !"("_tok)) 56 57 // R608 intrinsic-operator -> 58 // power-op | mult-op | add-op | concat-op | rel-op | 59 // not-op | and-op | or-op | equiv-op 60 // R610 extended-intrinsic-op -> intrinsic-operator 61 // These parsers must be ordered carefully to avoid misrecognition. 62 constexpr auto namedIntrinsicOperator{ 63 ".LT." >> pure(DefinedOperator::IntrinsicOperator::LT) || 64 ".LE." >> pure(DefinedOperator::IntrinsicOperator::LE) || 65 ".EQ." >> pure(DefinedOperator::IntrinsicOperator::EQ) || 66 ".NE." >> pure(DefinedOperator::IntrinsicOperator::NE) || 67 ".GE." >> pure(DefinedOperator::IntrinsicOperator::GE) || 68 ".GT." >> pure(DefinedOperator::IntrinsicOperator::GT) || 69 ".NOT." >> pure(DefinedOperator::IntrinsicOperator::NOT) || 70 ".AND." >> pure(DefinedOperator::IntrinsicOperator::AND) || 71 ".OR." >> pure(DefinedOperator::IntrinsicOperator::OR) || 72 ".EQV." >> pure(DefinedOperator::IntrinsicOperator::EQV) || 73 ".NEQV." >> pure(DefinedOperator::IntrinsicOperator::NEQV) || 74 extension<LanguageFeature::XOROperator>( 75 ".XOR." >> pure(DefinedOperator::IntrinsicOperator::NEQV)) || 76 extension<LanguageFeature::LogicalAbbreviations>( 77 ".N." >> pure(DefinedOperator::IntrinsicOperator::NOT) || 78 ".A." >> pure(DefinedOperator::IntrinsicOperator::AND) || 79 ".O." >> pure(DefinedOperator::IntrinsicOperator::OR) || 80 extension<LanguageFeature::XOROperator>( 81 ".X." >> pure(DefinedOperator::IntrinsicOperator::NEQV)))}; 82 83 constexpr auto intrinsicOperator{ 84 "**" >> pure(DefinedOperator::IntrinsicOperator::Power) || 85 "*" >> pure(DefinedOperator::IntrinsicOperator::Multiply) || 86 "//" >> pure(DefinedOperator::IntrinsicOperator::Concat) || 87 "/=" >> pure(DefinedOperator::IntrinsicOperator::NE) || 88 "/" >> pure(DefinedOperator::IntrinsicOperator::Divide) || 89 "+" >> pure(DefinedOperator::IntrinsicOperator::Add) || 90 "-" >> pure(DefinedOperator::IntrinsicOperator::Subtract) || 91 "<=" >> pure(DefinedOperator::IntrinsicOperator::LE) || 92 extension<LanguageFeature::AlternativeNE>( 93 "<>" >> pure(DefinedOperator::IntrinsicOperator::NE)) || 94 "<" >> pure(DefinedOperator::IntrinsicOperator::LT) || 95 "==" >> pure(DefinedOperator::IntrinsicOperator::EQ) || 96 ">=" >> pure(DefinedOperator::IntrinsicOperator::GE) || 97 ">" >> pure(DefinedOperator::IntrinsicOperator::GT) || 98 namedIntrinsicOperator}; 99 100 // R609 defined-operator -> 101 // defined-unary-op | defined-binary-op | extended-intrinsic-op 102 TYPE_PARSER(construct<DefinedOperator>(intrinsicOperator) || 103 construct<DefinedOperator>(definedOpName)) 104 105 // R505 implicit-part -> [implicit-part-stmt]... implicit-stmt 106 // TODO: Can overshoot; any trailing PARAMETER, FORMAT, & ENTRY 107 // statements after the last IMPLICIT should be transferred to the 108 // list of declaration-constructs. 109 TYPE_CONTEXT_PARSER("implicit part"_en_US, 110 construct<ImplicitPart>(many(Parser<ImplicitPartStmt>{}))) 111 112 // R506 implicit-part-stmt -> 113 // implicit-stmt | parameter-stmt | format-stmt | entry-stmt 114 TYPE_PARSER(first( 115 construct<ImplicitPartStmt>(statement(indirect(Parser<ImplicitStmt>{}))), 116 construct<ImplicitPartStmt>(statement(indirect(parameterStmt))), 117 construct<ImplicitPartStmt>(statement(indirect(oldParameterStmt))), 118 construct<ImplicitPartStmt>(statement(indirect(formatStmt))), 119 construct<ImplicitPartStmt>(statement(indirect(entryStmt))))) 120 121 // R512 internal-subprogram -> function-subprogram | subroutine-subprogram 122 // Internal subprograms are not program units, so their END statements 123 // can be followed by ';' and another statement on the same line. 124 TYPE_CONTEXT_PARSER("internal subprogram"_en_US, 125 (construct<InternalSubprogram>(indirect(functionSubprogram)) || 126 construct<InternalSubprogram>(indirect(subroutineSubprogram))) / 127 forceEndOfStmt) 128 129 // R511 internal-subprogram-part -> contains-stmt [internal-subprogram]... 130 TYPE_CONTEXT_PARSER("internal subprogram part"_en_US, 131 construct<InternalSubprogramPart>(statement(containsStmt), 132 many(StartNewSubprogram{} >> Parser<InternalSubprogram>{}))) 133 134 // R605 literal-constant -> 135 // int-literal-constant | real-literal-constant | 136 // complex-literal-constant | logical-literal-constant | 137 // char-literal-constant | boz-literal-constant 138 TYPE_PARSER( 139 first(construct<LiteralConstant>(Parser<HollerithLiteralConstant>{}), 140 construct<LiteralConstant>(realLiteralConstant), 141 construct<LiteralConstant>(intLiteralConstant), 142 construct<LiteralConstant>(Parser<ComplexLiteralConstant>{}), 143 construct<LiteralConstant>(Parser<BOZLiteralConstant>{}), 144 construct<LiteralConstant>(charLiteralConstant), 145 construct<LiteralConstant>(Parser<LogicalLiteralConstant>{}))) 146 147 // R606 named-constant -> name 148 TYPE_PARSER(construct<NamedConstant>(name)) 149 150 // R701 type-param-value -> scalar-int-expr | * | : 151 TYPE_PARSER(construct<TypeParamValue>(scalarIntExpr) || 152 construct<TypeParamValue>(star) || 153 construct<TypeParamValue>(construct<TypeParamValue::Deferred>(":"_tok))) 154 155 // R702 type-spec -> intrinsic-type-spec | derived-type-spec 156 // N.B. This type-spec production is one of two instances in the Fortran 157 // grammar where intrinsic types and bare derived type names can clash; 158 // the other is below in R703 declaration-type-spec. Look-ahead is required 159 // to disambiguate the cases where a derived type name begins with the name 160 // of an intrinsic type, e.g., REALITY. 161 TYPE_CONTEXT_PARSER("type spec"_en_US, 162 construct<TypeSpec>(intrinsicTypeSpec / lookAhead("::"_tok || ")"_tok)) || 163 construct<TypeSpec>(derivedTypeSpec)) 164 165 // R703 declaration-type-spec -> 166 // intrinsic-type-spec | TYPE ( intrinsic-type-spec ) | 167 // TYPE ( derived-type-spec ) | CLASS ( derived-type-spec ) | 168 // CLASS ( * ) | TYPE ( * ) 169 // N.B. It is critical to distribute "parenthesized()" over the alternatives 170 // for TYPE (...), rather than putting the alternatives within it, which 171 // would fail on "TYPE(real_derived)" with a misrecognition of "real" as an 172 // intrinsic-type-spec. 173 TYPE_CONTEXT_PARSER("declaration type spec"_en_US, 174 construct<DeclarationTypeSpec>(intrinsicTypeSpec) || 175 "TYPE" >> 176 (parenthesized(construct<DeclarationTypeSpec>(intrinsicTypeSpec)) || 177 parenthesized(construct<DeclarationTypeSpec>( 178 construct<DeclarationTypeSpec::Type>(derivedTypeSpec))) || 179 construct<DeclarationTypeSpec>( 180 "( * )" >> construct<DeclarationTypeSpec::TypeStar>())) || 181 "CLASS" >> parenthesized(construct<DeclarationTypeSpec>( 182 construct<DeclarationTypeSpec::Class>( 183 derivedTypeSpec)) || 184 construct<DeclarationTypeSpec>("*" >> 185 construct<DeclarationTypeSpec::ClassStar>())) || 186 extension<LanguageFeature::DECStructures>( 187 construct<DeclarationTypeSpec>( 188 construct<DeclarationTypeSpec::Record>( 189 "RECORD /" >> name / "/")))) 190 191 // R704 intrinsic-type-spec -> 192 // integer-type-spec | REAL [kind-selector] | DOUBLE PRECISION | 193 // COMPLEX [kind-selector] | CHARACTER [char-selector] | 194 // LOGICAL [kind-selector] 195 // Extensions: DOUBLE COMPLEX, BYTE 196 TYPE_CONTEXT_PARSER("intrinsic type spec"_en_US, 197 first(construct<IntrinsicTypeSpec>(integerTypeSpec), 198 construct<IntrinsicTypeSpec>( 199 construct<IntrinsicTypeSpec::Real>("REAL" >> maybe(kindSelector))), 200 construct<IntrinsicTypeSpec>("DOUBLE PRECISION" >> 201 construct<IntrinsicTypeSpec::DoublePrecision>()), 202 construct<IntrinsicTypeSpec>(construct<IntrinsicTypeSpec::Complex>( 203 "COMPLEX" >> maybe(kindSelector))), 204 construct<IntrinsicTypeSpec>(construct<IntrinsicTypeSpec::Character>( 205 "CHARACTER" >> maybe(Parser<CharSelector>{}))), 206 construct<IntrinsicTypeSpec>(construct<IntrinsicTypeSpec::Logical>( 207 "LOGICAL" >> maybe(kindSelector))), 208 construct<IntrinsicTypeSpec>("DOUBLE COMPLEX" >> 209 extension<LanguageFeature::DoubleComplex>( 210 construct<IntrinsicTypeSpec::DoubleComplex>())), 211 extension<LanguageFeature::Byte>( 212 construct<IntrinsicTypeSpec>(construct<IntegerTypeSpec>( 213 "BYTE" >> construct<std::optional<KindSelector>>(pure(1))))))) 214 215 // R705 integer-type-spec -> INTEGER [kind-selector] 216 TYPE_PARSER(construct<IntegerTypeSpec>("INTEGER" >> maybe(kindSelector))) 217 218 // R706 kind-selector -> ( [KIND =] scalar-int-constant-expr ) 219 // Legacy extension: kind-selector -> * digit-string 220 TYPE_PARSER(construct<KindSelector>( 221 parenthesized(maybe("KIND ="_tok) >> scalarIntConstantExpr)) || 222 extension<LanguageFeature::StarKind>(construct<KindSelector>( 223 construct<KindSelector::StarSize>("*" >> digitString64 / spaceCheck)))) 224 225 // R707 signed-int-literal-constant -> [sign] int-literal-constant 226 TYPE_PARSER(sourced(construct<SignedIntLiteralConstant>( 227 SignedIntLiteralConstantWithoutKind{}, maybe(underscore >> kindParam)))) 228 229 // R708 int-literal-constant -> digit-string [_ kind-param] 230 // The negated look-ahead for a trailing underscore prevents misrecognition 231 // when the digit string is a numeric kind parameter of a character literal. 232 TYPE_PARSER(construct<IntLiteralConstant>( 233 space >> digitString, maybe(underscore >> kindParam) / !underscore)) 234 235 // R709 kind-param -> digit-string | scalar-int-constant-name 236 TYPE_PARSER(construct<KindParam>(digitString64) || 237 construct<KindParam>(scalar(integer(constant(name))))) 238 239 // R712 sign -> + | - 240 // N.B. A sign constitutes a whole token, so a space is allowed in free form 241 // after the sign and before a real-literal-constant or 242 // complex-literal-constant. A sign is not a unary operator in these contexts. 243 constexpr auto sign{ 244 "+"_tok >> pure(Sign::Positive) || "-"_tok >> pure(Sign::Negative)}; 245 246 // R713 signed-real-literal-constant -> [sign] real-literal-constant 247 constexpr auto signedRealLiteralConstant{ 248 construct<SignedRealLiteralConstant>(maybe(sign), realLiteralConstant)}; 249 250 // R714 real-literal-constant -> 251 // significand [exponent-letter exponent] [_ kind-param] | 252 // digit-string exponent-letter exponent [_ kind-param] 253 // R715 significand -> digit-string . [digit-string] | . digit-string 254 // R716 exponent-letter -> E | D 255 // Extension: Q 256 // R717 exponent -> signed-digit-string 257 constexpr auto exponentPart{ 258 ("ed"_ch || extension<LanguageFeature::QuadPrecision>("q"_ch)) >> 259 SignedDigitString{}}; 260 261 TYPE_CONTEXT_PARSER("REAL literal constant"_en_US, 262 space >> 263 construct<RealLiteralConstant>( 264 sourced((digitString >> "."_ch >> 265 !(some(letter) >> 266 "."_ch /* don't misinterpret 1.AND. */) >> 267 maybe(digitString) >> maybe(exponentPart) >> ok || 268 "."_ch >> digitString >> maybe(exponentPart) >> ok || 269 digitString >> exponentPart >> ok) >> 270 construct<RealLiteralConstant::Real>()), 271 maybe(underscore >> kindParam))) 272 273 // R718 complex-literal-constant -> ( real-part , imag-part ) 274 TYPE_CONTEXT_PARSER("COMPLEX literal constant"_en_US, 275 parenthesized(construct<ComplexLiteralConstant>( 276 Parser<ComplexPart>{} / ",", Parser<ComplexPart>{}))) 277 278 // PGI/Intel extension: signed complex literal constant 279 TYPE_PARSER(construct<SignedComplexLiteralConstant>( 280 sign, Parser<ComplexLiteralConstant>{})) 281 282 // R719 real-part -> 283 // signed-int-literal-constant | signed-real-literal-constant | 284 // named-constant 285 // R720 imag-part -> 286 // signed-int-literal-constant | signed-real-literal-constant | 287 // named-constant 288 TYPE_PARSER(construct<ComplexPart>(signedRealLiteralConstant) || 289 construct<ComplexPart>(signedIntLiteralConstant) || 290 construct<ComplexPart>(namedConstant)) 291 292 // R721 char-selector -> 293 // length-selector | 294 // ( LEN = type-param-value , KIND = scalar-int-constant-expr ) | 295 // ( type-param-value , [KIND =] scalar-int-constant-expr ) | 296 // ( KIND = scalar-int-constant-expr [, LEN = type-param-value] ) 297 TYPE_PARSER(construct<CharSelector>(Parser<LengthSelector>{}) || 298 parenthesized(construct<CharSelector>( 299 "LEN =" >> typeParamValue, ", KIND =" >> scalarIntConstantExpr)) || 300 parenthesized(construct<CharSelector>( 301 typeParamValue / ",", maybe("KIND ="_tok) >> scalarIntConstantExpr)) || 302 parenthesized(construct<CharSelector>( 303 "KIND =" >> scalarIntConstantExpr, maybe(", LEN =" >> typeParamValue)))) 304 305 // R722 length-selector -> ( [LEN =] type-param-value ) | * char-length [,] 306 // N.B. The trailing [,] in the production is permitted by the Standard 307 // only in the context of a type-declaration-stmt, but even with that 308 // limitation, it would seem to be unnecessary and buggy to consume the comma 309 // here. 310 TYPE_PARSER(construct<LengthSelector>( 311 parenthesized(maybe("LEN ="_tok) >> typeParamValue)) || 312 construct<LengthSelector>("*" >> charLength /* / maybe(","_tok) */)) 313 314 // R723 char-length -> ( type-param-value ) | digit-string 315 TYPE_PARSER(construct<CharLength>(parenthesized(typeParamValue)) || 316 construct<CharLength>(space >> digitString64 / spaceCheck)) 317 318 // R724 char-literal-constant -> 319 // [kind-param _] ' [rep-char]... ' | 320 // [kind-param _] " [rep-char]... " 321 // "rep-char" is any non-control character. Doubled interior quotes are 322 // combined. Backslash escapes can be enabled. 323 // N.B. the parsing of "kind-param" takes care to not consume the '_'. 324 TYPE_CONTEXT_PARSER("CHARACTER literal constant"_en_US, 325 construct<CharLiteralConstant>( 326 kindParam / underscore, charLiteralConstantWithoutKind) || 327 construct<CharLiteralConstant>(construct<std::optional<KindParam>>(), 328 space >> charLiteralConstantWithoutKind)) 329 330 TYPE_CONTEXT_PARSER( 331 "Hollerith"_en_US, construct<HollerithLiteralConstant>(rawHollerithLiteral)) 332 333 // R725 logical-literal-constant -> 334 // .TRUE. [_ kind-param] | .FALSE. [_ kind-param] 335 // Also accept .T. and .F. as extensions. 336 TYPE_PARSER(construct<LogicalLiteralConstant>( 337 logicalTRUE, maybe(underscore >> kindParam)) || 338 construct<LogicalLiteralConstant>( 339 logicalFALSE, maybe(underscore >> kindParam))) 340 341 // R726 derived-type-def -> 342 // derived-type-stmt [type-param-def-stmt]... 343 // [private-or-sequence]... [component-part] 344 // [type-bound-procedure-part] end-type-stmt 345 // R735 component-part -> [component-def-stmt]... 346 TYPE_CONTEXT_PARSER("derived type definition"_en_US, 347 construct<DerivedTypeDef>(statement(Parser<DerivedTypeStmt>{}), 348 many(unambiguousStatement(Parser<TypeParamDefStmt>{})), 349 many(statement(Parser<PrivateOrSequence>{})), 350 many(inContext("component"_en_US, 351 unambiguousStatement(Parser<ComponentDefStmt>{}))), 352 maybe(Parser<TypeBoundProcedurePart>{}), 353 statement(Parser<EndTypeStmt>{}))) 354 355 // R727 derived-type-stmt -> 356 // TYPE [[, type-attr-spec-list] ::] type-name [( 357 // type-param-name-list )] 358 TYPE_CONTEXT_PARSER("TYPE statement"_en_US, 359 construct<DerivedTypeStmt>( 360 "TYPE" >> optionalListBeforeColons(Parser<TypeAttrSpec>{}), name, 361 defaulted(parenthesized(nonemptyList(name))))) 362 363 // R728 type-attr-spec -> 364 // ABSTRACT | access-spec | BIND(C) | EXTENDS ( parent-type-name ) 365 TYPE_PARSER(construct<TypeAttrSpec>(construct<Abstract>("ABSTRACT"_tok)) || 366 construct<TypeAttrSpec>(construct<TypeAttrSpec::BindC>("BIND ( C )"_tok)) || 367 construct<TypeAttrSpec>( 368 construct<TypeAttrSpec::Extends>("EXTENDS" >> parenthesized(name))) || 369 construct<TypeAttrSpec>(accessSpec)) 370 371 // R729 private-or-sequence -> private-components-stmt | sequence-stmt 372 TYPE_PARSER(construct<PrivateOrSequence>(Parser<PrivateStmt>{}) || 373 construct<PrivateOrSequence>(Parser<SequenceStmt>{})) 374 375 // R730 end-type-stmt -> END TYPE [type-name] 376 TYPE_PARSER(construct<EndTypeStmt>( 377 recovery("END TYPE" >> maybe(name), endStmtErrorRecovery))) 378 379 // R731 sequence-stmt -> SEQUENCE 380 TYPE_PARSER(construct<SequenceStmt>("SEQUENCE"_tok)) 381 382 // R732 type-param-def-stmt -> 383 // integer-type-spec , type-param-attr-spec :: type-param-decl-list 384 // R734 type-param-attr-spec -> KIND | LEN 385 constexpr auto kindOrLen{"KIND" >> pure(common::TypeParamAttr::Kind) || 386 "LEN" >> pure(common::TypeParamAttr::Len)}; 387 TYPE_PARSER(construct<TypeParamDefStmt>(integerTypeSpec / ",", kindOrLen, 388 "::" >> nonemptyList("expected type parameter declarations"_err_en_US, 389 Parser<TypeParamDecl>{}))) 390 391 // R733 type-param-decl -> type-param-name [= scalar-int-constant-expr] 392 TYPE_PARSER(construct<TypeParamDecl>(name, maybe("=" >> scalarIntConstantExpr))) 393 394 // R736 component-def-stmt -> data-component-def-stmt | 395 // proc-component-def-stmt 396 // Accidental extension not enabled here: PGI accepts type-param-def-stmt in 397 // component-part of derived-type-def. 398 TYPE_PARSER(recovery( 399 withMessage("expected component definition"_err_en_US, 400 first(construct<ComponentDefStmt>(Parser<DataComponentDefStmt>{}), 401 construct<ComponentDefStmt>(Parser<ProcComponentDefStmt>{}))), 402 construct<ComponentDefStmt>(inStmtErrorRecovery))) 403 404 // R737 data-component-def-stmt -> 405 // declaration-type-spec [[, component-attr-spec-list] ::] 406 // component-decl-list 407 // N.B. The standard requires double colons if there's an initializer. 408 TYPE_PARSER(construct<DataComponentDefStmt>(declarationTypeSpec, 409 optionalListBeforeColons(Parser<ComponentAttrSpec>{}), 410 nonemptyList( 411 "expected component declarations"_err_en_US, Parser<ComponentDecl>{}))) 412 413 // R738 component-attr-spec -> 414 // access-spec | ALLOCATABLE | 415 // CODIMENSION lbracket coarray-spec rbracket | 416 // CONTIGUOUS | DIMENSION ( component-array-spec ) | POINTER 417 TYPE_PARSER(construct<ComponentAttrSpec>(accessSpec) || 418 construct<ComponentAttrSpec>(allocatable) || 419 construct<ComponentAttrSpec>("CODIMENSION" >> coarraySpec) || 420 construct<ComponentAttrSpec>(contiguous) || 421 construct<ComponentAttrSpec>("DIMENSION" >> Parser<ComponentArraySpec>{}) || 422 construct<ComponentAttrSpec>(pointer) || 423 construct<ComponentAttrSpec>(recovery( 424 fail<ErrorRecovery>( 425 "type parameter definitions must appear before component declarations"_err_en_US), 426 kindOrLen >> construct<ErrorRecovery>()))) 427 428 // R739 component-decl -> 429 // component-name [( component-array-spec )] 430 // [lbracket coarray-spec rbracket] [* char-length] 431 // [component-initialization] 432 TYPE_CONTEXT_PARSER("component declaration"_en_US, 433 construct<ComponentDecl>(name, maybe(Parser<ComponentArraySpec>{}), 434 maybe(coarraySpec), maybe("*" >> charLength), maybe(initialization))) 435 436 // R740 component-array-spec -> 437 // explicit-shape-spec-list | deferred-shape-spec-list 438 // N.B. Parenthesized here rather than around references to this production. 439 TYPE_PARSER(construct<ComponentArraySpec>(parenthesized( 440 nonemptyList("expected explicit shape specifications"_err_en_US, 441 explicitShapeSpec))) || 442 construct<ComponentArraySpec>(parenthesized(deferredShapeSpecList))) 443 444 // R741 proc-component-def-stmt -> 445 // PROCEDURE ( [proc-interface] ) , proc-component-attr-spec-list 446 // :: proc-decl-list 447 TYPE_CONTEXT_PARSER("PROCEDURE component definition statement"_en_US, 448 construct<ProcComponentDefStmt>( 449 "PROCEDURE" >> parenthesized(maybe(procInterface)), 450 localRecovery("expected PROCEDURE component attributes"_err_en_US, 451 "," >> nonemptyList(Parser<ProcComponentAttrSpec>{}), ok), 452 localRecovery("expected PROCEDURE declarations"_err_en_US, 453 "::" >> nonemptyList(procDecl), SkipTo<'\n'>{}))) 454 455 // R742 proc-component-attr-spec -> 456 // access-spec | NOPASS | PASS [(arg-name)] | POINTER 457 constexpr auto noPass{construct<NoPass>("NOPASS"_tok)}; 458 constexpr auto pass{construct<Pass>("PASS" >> maybe(parenthesized(name)))}; 459 TYPE_PARSER(construct<ProcComponentAttrSpec>(accessSpec) || 460 construct<ProcComponentAttrSpec>(noPass) || 461 construct<ProcComponentAttrSpec>(pass) || 462 construct<ProcComponentAttrSpec>(pointer)) 463 464 // R744 initial-data-target -> designator 465 constexpr auto initialDataTarget{indirect(designator)}; 466 467 // R743 component-initialization -> 468 // = constant-expr | => null-init | => initial-data-target 469 // R805 initialization -> 470 // = constant-expr | => null-init | => initial-data-target 471 // Universal extension: initialization -> / data-stmt-value-list / 472 TYPE_PARSER(construct<Initialization>("=>" >> nullInit) || 473 construct<Initialization>("=>" >> initialDataTarget) || 474 construct<Initialization>("=" >> constantExpr) || 475 extension<LanguageFeature::SlashInitialization>(construct<Initialization>( 476 "/" >> nonemptyList("expected values"_err_en_US, 477 indirect(Parser<DataStmtValue>{})) / 478 "/"))) 479 480 // R745 private-components-stmt -> PRIVATE 481 // R747 binding-private-stmt -> PRIVATE 482 TYPE_PARSER(construct<PrivateStmt>("PRIVATE"_tok)) 483 484 // R746 type-bound-procedure-part -> 485 // contains-stmt [binding-private-stmt] [type-bound-proc-binding]... 486 TYPE_CONTEXT_PARSER("type bound procedure part"_en_US, 487 construct<TypeBoundProcedurePart>(statement(containsStmt), 488 maybe(statement(Parser<PrivateStmt>{})), 489 many(statement(Parser<TypeBoundProcBinding>{})))) 490 491 // R748 type-bound-proc-binding -> 492 // type-bound-procedure-stmt | type-bound-generic-stmt | 493 // final-procedure-stmt 494 TYPE_CONTEXT_PARSER("type bound procedure binding"_en_US, 495 recovery( 496 first(construct<TypeBoundProcBinding>(Parser<TypeBoundProcedureStmt>{}), 497 construct<TypeBoundProcBinding>(Parser<TypeBoundGenericStmt>{}), 498 construct<TypeBoundProcBinding>(Parser<FinalProcedureStmt>{})), 499 construct<TypeBoundProcBinding>( 500 !"END"_tok >> SkipTo<'\n'>{} >> construct<ErrorRecovery>()))) 501 502 // R749 type-bound-procedure-stmt -> 503 // PROCEDURE [[, bind-attr-list] ::] type-bound-proc-decl-list | 504 // PROCEDURE ( interface-name ) , bind-attr-list :: binding-name-list 505 TYPE_CONTEXT_PARSER("type bound PROCEDURE statement"_en_US, 506 "PROCEDURE" >> 507 (construct<TypeBoundProcedureStmt>( 508 construct<TypeBoundProcedureStmt::WithInterface>( 509 parenthesized(name), 510 localRecovery("expected list of binding attributes"_err_en_US, 511 "," >> nonemptyList(Parser<BindAttr>{}), ok), 512 localRecovery("expected list of binding names"_err_en_US, 513 "::" >> listOfNames, SkipTo<'\n'>{}))) || 514 construct<TypeBoundProcedureStmt>( 515 construct<TypeBoundProcedureStmt::WithoutInterface>( 516 optionalListBeforeColons(Parser<BindAttr>{}), 517 nonemptyList( 518 "expected type bound procedure declarations"_err_en_US, 519 Parser<TypeBoundProcDecl>{}))))) 520 521 // R750 type-bound-proc-decl -> binding-name [=> procedure-name] 522 TYPE_PARSER(construct<TypeBoundProcDecl>(name, maybe("=>" >> name))) 523 524 // R751 type-bound-generic-stmt -> 525 // GENERIC [, access-spec] :: generic-spec => binding-name-list 526 TYPE_CONTEXT_PARSER("type bound GENERIC statement"_en_US, 527 construct<TypeBoundGenericStmt>("GENERIC" >> maybe("," >> accessSpec), 528 "::" >> indirect(genericSpec), "=>" >> listOfNames)) 529 530 // R752 bind-attr -> 531 // access-spec | DEFERRED | NON_OVERRIDABLE | NOPASS | PASS [(arg-name)] 532 TYPE_PARSER(construct<BindAttr>(accessSpec) || 533 construct<BindAttr>(construct<BindAttr::Deferred>("DEFERRED"_tok)) || 534 construct<BindAttr>( 535 construct<BindAttr::Non_Overridable>("NON_OVERRIDABLE"_tok)) || 536 construct<BindAttr>(noPass) || construct<BindAttr>(pass)) 537 538 // R753 final-procedure-stmt -> FINAL [::] final-subroutine-name-list 539 TYPE_CONTEXT_PARSER("FINAL statement"_en_US, 540 construct<FinalProcedureStmt>("FINAL" >> maybe("::"_tok) >> listOfNames)) 541 542 // R754 derived-type-spec -> type-name [(type-param-spec-list)] 543 TYPE_PARSER(construct<DerivedTypeSpec>(name, 544 defaulted(parenthesized(nonemptyList( 545 "expected type parameters"_err_en_US, Parser<TypeParamSpec>{}))))) 546 547 // R755 type-param-spec -> [keyword =] type-param-value 548 TYPE_PARSER(construct<TypeParamSpec>(maybe(keyword / "="), typeParamValue)) 549 550 // R756 structure-constructor -> derived-type-spec ( [component-spec-list] ) 551 TYPE_PARSER((construct<StructureConstructor>(derivedTypeSpec, 552 parenthesized(optionalList(Parser<ComponentSpec>{}))) || 553 // This alternative corrects misrecognition of the 554 // component-spec-list as the type-param-spec-list in 555 // derived-type-spec. 556 construct<StructureConstructor>( 557 construct<DerivedTypeSpec>( 558 name, construct<std::list<TypeParamSpec>>()), 559 parenthesized(optionalList(Parser<ComponentSpec>{})))) / 560 !"("_tok) 561 562 // R757 component-spec -> [keyword =] component-data-source 563 TYPE_PARSER(construct<ComponentSpec>( 564 maybe(keyword / "="), Parser<ComponentDataSource>{})) 565 566 // R758 component-data-source -> expr | data-target | proc-target 567 TYPE_PARSER(construct<ComponentDataSource>(indirect(expr))) 568 569 // R759 enum-def -> 570 // enum-def-stmt enumerator-def-stmt [enumerator-def-stmt]... 571 // end-enum-stmt 572 TYPE_CONTEXT_PARSER("enum definition"_en_US, 573 construct<EnumDef>(statement(Parser<EnumDefStmt>{}), 574 some(unambiguousStatement(Parser<EnumeratorDefStmt>{})), 575 statement(Parser<EndEnumStmt>{}))) 576 577 // R760 enum-def-stmt -> ENUM, BIND(C) 578 TYPE_PARSER(construct<EnumDefStmt>("ENUM , BIND ( C )"_tok)) 579 580 // R761 enumerator-def-stmt -> ENUMERATOR [::] enumerator-list 581 TYPE_CONTEXT_PARSER("ENUMERATOR statement"_en_US, 582 construct<EnumeratorDefStmt>("ENUMERATOR" >> maybe("::"_tok) >> 583 nonemptyList("expected enumerators"_err_en_US, Parser<Enumerator>{}))) 584 585 // R762 enumerator -> named-constant [= scalar-int-constant-expr] 586 TYPE_PARSER( 587 construct<Enumerator>(namedConstant, maybe("=" >> scalarIntConstantExpr))) 588 589 // R763 end-enum-stmt -> END ENUM 590 TYPE_PARSER(recovery("END ENUM"_tok, "END" >> SkipPast<'\n'>{}) >> 591 construct<EndEnumStmt>()) 592 593 // R801 type-declaration-stmt -> 594 // declaration-type-spec [[, attr-spec]... ::] entity-decl-list 595 constexpr auto entityDeclWithoutEqInit{construct<EntityDecl>(name, 596 maybe(arraySpec), maybe(coarraySpec), maybe("*" >> charLength), 597 !"="_tok >> maybe(initialization))}; // old-style REAL A/0/ still works 598 TYPE_PARSER( 599 construct<TypeDeclarationStmt>(declarationTypeSpec, 600 defaulted("," >> nonemptyList(Parser<AttrSpec>{})) / "::", 601 nonemptyList("expected entity declarations"_err_en_US, entityDecl)) || 602 // C806: no initializers allowed without colons ("REALA=1" is ambiguous) 603 construct<TypeDeclarationStmt>(declarationTypeSpec, 604 construct<std::list<AttrSpec>>(), 605 nonemptyList("expected entity declarations"_err_en_US, 606 entityDeclWithoutEqInit)) || 607 // PGI-only extension: comma in place of doubled colons 608 extension<LanguageFeature::MissingColons>(construct<TypeDeclarationStmt>( 609 declarationTypeSpec, defaulted("," >> nonemptyList(Parser<AttrSpec>{})), 610 withMessage("expected entity declarations"_err_en_US, 611 "," >> nonemptyList(entityDecl))))) 612 613 // R802 attr-spec -> 614 // access-spec | ALLOCATABLE | ASYNCHRONOUS | 615 // CODIMENSION lbracket coarray-spec rbracket | CONTIGUOUS | 616 // DIMENSION ( array-spec ) | EXTERNAL | INTENT ( intent-spec ) | 617 // INTRINSIC | language-binding-spec | OPTIONAL | PARAMETER | POINTER | 618 // PROTECTED | SAVE | TARGET | VALUE | VOLATILE 619 TYPE_PARSER(construct<AttrSpec>(accessSpec) || 620 construct<AttrSpec>(allocatable) || 621 construct<AttrSpec>(construct<Asynchronous>("ASYNCHRONOUS"_tok)) || 622 construct<AttrSpec>("CODIMENSION" >> coarraySpec) || 623 construct<AttrSpec>(contiguous) || 624 construct<AttrSpec>("DIMENSION" >> arraySpec) || 625 construct<AttrSpec>(construct<External>("EXTERNAL"_tok)) || 626 construct<AttrSpec>("INTENT" >> parenthesized(intentSpec)) || 627 construct<AttrSpec>(construct<Intrinsic>("INTRINSIC"_tok)) || 628 construct<AttrSpec>(languageBindingSpec) || construct<AttrSpec>(optional) || 629 construct<AttrSpec>(construct<Parameter>("PARAMETER"_tok)) || 630 construct<AttrSpec>(pointer) || construct<AttrSpec>(protectedAttr) || 631 construct<AttrSpec>(save) || 632 construct<AttrSpec>(construct<Target>("TARGET"_tok)) || 633 construct<AttrSpec>(construct<Value>("VALUE"_tok)) || 634 construct<AttrSpec>(construct<Volatile>("VOLATILE"_tok))) 635 636 // R804 object-name -> name 637 constexpr auto objectName{name}; 638 639 // R803 entity-decl -> 640 // object-name [( array-spec )] [lbracket coarray-spec rbracket] 641 // [* char-length] [initialization] | 642 // function-name [* char-length] 643 TYPE_PARSER(construct<EntityDecl>(objectName, maybe(arraySpec), 644 maybe(coarraySpec), maybe("*" >> charLength), maybe(initialization))) 645 646 // R806 null-init -> function-reference 647 // TODO: confirm in semantics that NULL still intrinsic in this scope 648 TYPE_PARSER(construct<NullInit>("NULL ( )"_tok) / !"("_tok) 649 650 // R807 access-spec -> PUBLIC | PRIVATE 651 TYPE_PARSER(construct<AccessSpec>("PUBLIC" >> pure(AccessSpec::Kind::Public)) || 652 construct<AccessSpec>("PRIVATE" >> pure(AccessSpec::Kind::Private))) 653 654 // R808 language-binding-spec -> 655 // BIND ( C [, NAME = scalar-default-char-constant-expr] ) 656 // R1528 proc-language-binding-spec -> language-binding-spec 657 TYPE_PARSER(construct<LanguageBindingSpec>( 658 "BIND ( C" >> maybe(", NAME =" >> scalarDefaultCharConstantExpr) / ")")) 659 660 // R809 coarray-spec -> deferred-coshape-spec-list | explicit-coshape-spec 661 // N.B. Bracketed here rather than around references, for consistency with 662 // array-spec. 663 TYPE_PARSER( 664 construct<CoarraySpec>(bracketed(Parser<DeferredCoshapeSpecList>{})) || 665 construct<CoarraySpec>(bracketed(Parser<ExplicitCoshapeSpec>{}))) 666 667 // R810 deferred-coshape-spec -> : 668 // deferred-coshape-spec-list - just a list of colons 669 inline int listLength(std::list<Success> &&xs) { return xs.size(); } 670 671 TYPE_PARSER(construct<DeferredCoshapeSpecList>( 672 applyFunction(listLength, nonemptyList(":"_tok)))) 673 674 // R811 explicit-coshape-spec -> 675 // [[lower-cobound :] upper-cobound ,]... [lower-cobound :] * 676 // R812 lower-cobound -> specification-expr 677 // R813 upper-cobound -> specification-expr 678 TYPE_PARSER(construct<ExplicitCoshapeSpec>( 679 many(explicitShapeSpec / ","), maybe(specificationExpr / ":") / "*")) 680 681 // R815 array-spec -> 682 // explicit-shape-spec-list | assumed-shape-spec-list | 683 // deferred-shape-spec-list | assumed-size-spec | implied-shape-spec | 684 // implied-shape-or-assumed-size-spec | assumed-rank-spec 685 // N.B. Parenthesized here rather than around references to avoid 686 // a need for forced look-ahead. 687 // Shape specs that could be deferred-shape-spec or assumed-shape-spec 688 // (e.g. '(:,:)') are parsed as the former. 689 TYPE_PARSER( 690 construct<ArraySpec>(parenthesized(nonemptyList(explicitShapeSpec))) || 691 construct<ArraySpec>(parenthesized(deferredShapeSpecList)) || 692 construct<ArraySpec>( 693 parenthesized(nonemptyList(Parser<AssumedShapeSpec>{}))) || 694 construct<ArraySpec>(parenthesized(Parser<AssumedSizeSpec>{})) || 695 construct<ArraySpec>(parenthesized(Parser<ImpliedShapeSpec>{})) || 696 construct<ArraySpec>(parenthesized(Parser<AssumedRankSpec>{}))) 697 698 // R816 explicit-shape-spec -> [lower-bound :] upper-bound 699 // R817 lower-bound -> specification-expr 700 // R818 upper-bound -> specification-expr 701 TYPE_PARSER(construct<ExplicitShapeSpec>( 702 maybe(specificationExpr / ":"), specificationExpr)) 703 704 // R819 assumed-shape-spec -> [lower-bound] : 705 TYPE_PARSER(construct<AssumedShapeSpec>(maybe(specificationExpr) / ":")) 706 707 // R820 deferred-shape-spec -> : 708 // deferred-shape-spec-list - just a list of colons 709 TYPE_PARSER(construct<DeferredShapeSpecList>( 710 applyFunction(listLength, nonemptyList(":"_tok)))) 711 712 // R821 assumed-implied-spec -> [lower-bound :] * 713 TYPE_PARSER(construct<AssumedImpliedSpec>(maybe(specificationExpr / ":") / "*")) 714 715 // R822 assumed-size-spec -> explicit-shape-spec-list , assumed-implied-spec 716 TYPE_PARSER(construct<AssumedSizeSpec>( 717 nonemptyList(explicitShapeSpec) / ",", assumedImpliedSpec)) 718 719 // R823 implied-shape-or-assumed-size-spec -> assumed-implied-spec 720 // R824 implied-shape-spec -> assumed-implied-spec , assumed-implied-spec-list 721 // I.e., when the assumed-implied-spec-list has a single item, it constitutes an 722 // implied-shape-or-assumed-size-spec; otherwise, an implied-shape-spec. 723 TYPE_PARSER(construct<ImpliedShapeSpec>(nonemptyList(assumedImpliedSpec))) 724 725 // R825 assumed-rank-spec -> .. 726 TYPE_PARSER(construct<AssumedRankSpec>(".."_tok)) 727 728 // R826 intent-spec -> IN | OUT | INOUT 729 TYPE_PARSER(construct<IntentSpec>("IN OUT" >> pure(IntentSpec::Intent::InOut) || 730 "IN" >> pure(IntentSpec::Intent::In) || 731 "OUT" >> pure(IntentSpec::Intent::Out))) 732 733 // R827 access-stmt -> access-spec [[::] access-id-list] 734 TYPE_PARSER(construct<AccessStmt>(accessSpec, 735 defaulted(maybe("::"_tok) >> 736 nonemptyList("expected names and generic specifications"_err_en_US, 737 Parser<AccessId>{})))) 738 739 // R828 access-id -> access-name | generic-spec 740 TYPE_PARSER(construct<AccessId>(indirect(genericSpec)) || 741 construct<AccessId>(name)) // initially ambiguous with genericSpec 742 743 // R829 allocatable-stmt -> ALLOCATABLE [::] allocatable-decl-list 744 TYPE_PARSER(construct<AllocatableStmt>("ALLOCATABLE" >> maybe("::"_tok) >> 745 nonemptyList( 746 "expected object declarations"_err_en_US, Parser<ObjectDecl>{}))) 747 748 // R830 allocatable-decl -> 749 // object-name [( array-spec )] [lbracket coarray-spec rbracket] 750 // R860 target-decl -> 751 // object-name [( array-spec )] [lbracket coarray-spec rbracket] 752 TYPE_PARSER( 753 construct<ObjectDecl>(objectName, maybe(arraySpec), maybe(coarraySpec))) 754 755 // R831 asynchronous-stmt -> ASYNCHRONOUS [::] object-name-list 756 TYPE_PARSER(construct<AsynchronousStmt>("ASYNCHRONOUS" >> maybe("::"_tok) >> 757 nonemptyList("expected object names"_err_en_US, objectName))) 758 759 // R832 bind-stmt -> language-binding-spec [::] bind-entity-list 760 TYPE_PARSER(construct<BindStmt>(languageBindingSpec / maybe("::"_tok), 761 nonemptyList("expected bind entities"_err_en_US, Parser<BindEntity>{}))) 762 763 // R833 bind-entity -> entity-name | / common-block-name / 764 TYPE_PARSER(construct<BindEntity>(pure(BindEntity::Kind::Object), name) || 765 construct<BindEntity>("/" >> pure(BindEntity::Kind::Common), name / "/")) 766 767 // R834 codimension-stmt -> CODIMENSION [::] codimension-decl-list 768 TYPE_PARSER(construct<CodimensionStmt>("CODIMENSION" >> maybe("::"_tok) >> 769 nonemptyList("expected codimension declarations"_err_en_US, 770 Parser<CodimensionDecl>{}))) 771 772 // R835 codimension-decl -> coarray-name lbracket coarray-spec rbracket 773 TYPE_PARSER(construct<CodimensionDecl>(name, coarraySpec)) 774 775 // R836 contiguous-stmt -> CONTIGUOUS [::] object-name-list 776 TYPE_PARSER(construct<ContiguousStmt>("CONTIGUOUS" >> maybe("::"_tok) >> 777 nonemptyList("expected object names"_err_en_US, objectName))) 778 779 // R837 data-stmt -> DATA data-stmt-set [[,] data-stmt-set]... 780 TYPE_CONTEXT_PARSER("DATA statement"_en_US, 781 construct<DataStmt>( 782 "DATA" >> nonemptySeparated(Parser<DataStmtSet>{}, maybe(","_tok)))) 783 784 // R838 data-stmt-set -> data-stmt-object-list / data-stmt-value-list / 785 TYPE_PARSER(construct<DataStmtSet>( 786 nonemptyList( 787 "expected DATA statement objects"_err_en_US, Parser<DataStmtObject>{}), 788 withMessage("expected DATA statement value list"_err_en_US, 789 "/"_tok >> nonemptyList("expected DATA statement values"_err_en_US, 790 Parser<DataStmtValue>{})) / 791 "/")) 792 793 // R839 data-stmt-object -> variable | data-implied-do 794 TYPE_PARSER(construct<DataStmtObject>(indirect(variable)) || 795 construct<DataStmtObject>(dataImpliedDo)) 796 797 // R840 data-implied-do -> 798 // ( data-i-do-object-list , [integer-type-spec ::] data-i-do-variable 799 // = scalar-int-constant-expr , scalar-int-constant-expr 800 // [, scalar-int-constant-expr] ) 801 // R842 data-i-do-variable -> do-variable 802 TYPE_PARSER(parenthesized(construct<DataImpliedDo>( 803 nonemptyList(Parser<DataIDoObject>{} / lookAhead(","_tok)) / ",", 804 maybe(integerTypeSpec / "::"), loopBounds(scalarIntConstantExpr)))) 805 806 // R841 data-i-do-object -> 807 // array-element | scalar-structure-component | data-implied-do 808 TYPE_PARSER(construct<DataIDoObject>(scalar(indirect(designator))) || 809 construct<DataIDoObject>(indirect(dataImpliedDo))) 810 811 // R843 data-stmt-value -> [data-stmt-repeat *] data-stmt-constant 812 TYPE_PARSER(construct<DataStmtValue>( 813 maybe(Parser<DataStmtRepeat>{} / "*"), Parser<DataStmtConstant>{})) 814 815 // R847 constant-subobject -> designator 816 // R846 int-constant-subobject -> constant-subobject 817 constexpr auto constantSubobject{constant(indirect(designator))}; 818 819 // R844 data-stmt-repeat -> scalar-int-constant | scalar-int-constant-subobject 820 // R607 int-constant -> constant 821 // Factored into: constant -> literal-constant -> int-literal-constant 822 // The named-constant alternative of constant is subsumed by constant-subobject 823 TYPE_PARSER(construct<DataStmtRepeat>(intLiteralConstant) || 824 construct<DataStmtRepeat>(scalar(integer(constantSubobject)))) 825 826 // R845 data-stmt-constant -> 827 // scalar-constant | scalar-constant-subobject | 828 // signed-int-literal-constant | signed-real-literal-constant | 829 // null-init | initial-data-target | structure-constructor 830 // TODO: Some structure constructors can be misrecognized as array 831 // references into constant subobjects. 832 TYPE_PARSER(first(construct<DataStmtConstant>(scalar(Parser<ConstantValue>{})), 833 construct<DataStmtConstant>(nullInit), 834 construct<DataStmtConstant>(scalar(constantSubobject)) / !"("_tok, 835 construct<DataStmtConstant>(Parser<StructureConstructor>{}), 836 construct<DataStmtConstant>(signedRealLiteralConstant), 837 construct<DataStmtConstant>(signedIntLiteralConstant), 838 extension<LanguageFeature::SignedComplexLiteral>( 839 construct<DataStmtConstant>(Parser<SignedComplexLiteralConstant>{})), 840 construct<DataStmtConstant>(initialDataTarget))) 841 842 // R848 dimension-stmt -> 843 // DIMENSION [::] array-name ( array-spec ) 844 // [, array-name ( array-spec )]... 845 TYPE_CONTEXT_PARSER("DIMENSION statement"_en_US, 846 construct<DimensionStmt>("DIMENSION" >> maybe("::"_tok) >> 847 nonemptyList("expected array specifications"_err_en_US, 848 construct<DimensionStmt::Declaration>(name, arraySpec)))) 849 850 // R849 intent-stmt -> INTENT ( intent-spec ) [::] dummy-arg-name-list 851 TYPE_CONTEXT_PARSER("INTENT statement"_en_US, 852 construct<IntentStmt>( 853 "INTENT" >> parenthesized(intentSpec) / maybe("::"_tok), listOfNames)) 854 855 // R850 optional-stmt -> OPTIONAL [::] dummy-arg-name-list 856 TYPE_PARSER( 857 construct<OptionalStmt>("OPTIONAL" >> maybe("::"_tok) >> listOfNames)) 858 859 // R851 parameter-stmt -> PARAMETER ( named-constant-def-list ) 860 // Legacy extension: omitted parentheses, no implicit typing from names 861 TYPE_CONTEXT_PARSER("PARAMETER statement"_en_US, 862 construct<ParameterStmt>( 863 "PARAMETER" >> parenthesized(nonemptyList(Parser<NamedConstantDef>{})))) 864 TYPE_CONTEXT_PARSER("old style PARAMETER statement"_en_US, 865 extension<LanguageFeature::OldStyleParameter>(construct<OldParameterStmt>( 866 "PARAMETER" >> nonemptyList(Parser<NamedConstantDef>{})))) 867 868 // R852 named-constant-def -> named-constant = constant-expr 869 TYPE_PARSER(construct<NamedConstantDef>(namedConstant, "=" >> constantExpr)) 870 871 // R853 pointer-stmt -> POINTER [::] pointer-decl-list 872 TYPE_PARSER(construct<PointerStmt>("POINTER" >> maybe("::"_tok) >> 873 nonemptyList( 874 "expected pointer declarations"_err_en_US, Parser<PointerDecl>{}))) 875 876 // R854 pointer-decl -> 877 // object-name [( deferred-shape-spec-list )] | proc-entity-name 878 TYPE_PARSER( 879 construct<PointerDecl>(name, maybe(parenthesized(deferredShapeSpecList)))) 880 881 // R855 protected-stmt -> PROTECTED [::] entity-name-list 882 TYPE_PARSER( 883 construct<ProtectedStmt>("PROTECTED" >> maybe("::"_tok) >> listOfNames)) 884 885 // R856 save-stmt -> SAVE [[::] saved-entity-list] 886 TYPE_PARSER(construct<SaveStmt>( 887 "SAVE" >> defaulted(maybe("::"_tok) >> 888 nonemptyList("expected SAVE entities"_err_en_US, 889 Parser<SavedEntity>{})))) 890 891 // R857 saved-entity -> object-name | proc-pointer-name | / common-block-name / 892 // R858 proc-pointer-name -> name 893 TYPE_PARSER(construct<SavedEntity>(pure(SavedEntity::Kind::Entity), name) || 894 construct<SavedEntity>("/" >> pure(SavedEntity::Kind::Common), name / "/")) 895 896 // R859 target-stmt -> TARGET [::] target-decl-list 897 TYPE_PARSER(construct<TargetStmt>("TARGET" >> maybe("::"_tok) >> 898 nonemptyList("expected objects"_err_en_US, Parser<ObjectDecl>{}))) 899 900 // R861 value-stmt -> VALUE [::] dummy-arg-name-list 901 TYPE_PARSER(construct<ValueStmt>("VALUE" >> maybe("::"_tok) >> listOfNames)) 902 903 // R862 volatile-stmt -> VOLATILE [::] object-name-list 904 TYPE_PARSER(construct<VolatileStmt>("VOLATILE" >> maybe("::"_tok) >> 905 nonemptyList("expected object names"_err_en_US, objectName))) 906 907 // R866 implicit-name-spec -> EXTERNAL | TYPE 908 constexpr auto implicitNameSpec{ 909 "EXTERNAL" >> pure(ImplicitStmt::ImplicitNoneNameSpec::External) || 910 "TYPE" >> pure(ImplicitStmt::ImplicitNoneNameSpec::Type)}; 911 912 // R863 implicit-stmt -> 913 // IMPLICIT implicit-spec-list | 914 // IMPLICIT NONE [( [implicit-name-spec-list] )] 915 TYPE_CONTEXT_PARSER("IMPLICIT statement"_en_US, 916 construct<ImplicitStmt>( 917 "IMPLICIT" >> nonemptyList("expected IMPLICIT specifications"_err_en_US, 918 Parser<ImplicitSpec>{})) || 919 construct<ImplicitStmt>("IMPLICIT NONE"_sptok >> 920 defaulted(parenthesized(optionalList(implicitNameSpec))))) 921 922 // R864 implicit-spec -> declaration-type-spec ( letter-spec-list ) 923 // The variant form of declarationTypeSpec is meant to avoid misrecognition 924 // of a letter-spec as a simple parenthesized expression for kind or character 925 // length, e.g., PARAMETER(I=5,N=1); IMPLICIT REAL(I-N)(O-Z) vs. 926 // IMPLICIT REAL(I-N). The variant form needs to attempt to reparse only 927 // types with optional parenthesized kind/length expressions, so derived 928 // type specs, DOUBLE PRECISION, and DOUBLE COMPLEX need not be considered. 929 constexpr auto noKindSelector{construct<std::optional<KindSelector>>()}; 930 constexpr auto implicitSpecDeclarationTypeSpecRetry{ 931 construct<DeclarationTypeSpec>(first( 932 construct<IntrinsicTypeSpec>( 933 construct<IntegerTypeSpec>("INTEGER" >> noKindSelector)), 934 construct<IntrinsicTypeSpec>( 935 construct<IntrinsicTypeSpec::Real>("REAL" >> noKindSelector)), 936 construct<IntrinsicTypeSpec>( 937 construct<IntrinsicTypeSpec::Complex>("COMPLEX" >> noKindSelector)), 938 construct<IntrinsicTypeSpec>(construct<IntrinsicTypeSpec::Character>( 939 "CHARACTER" >> construct<std::optional<CharSelector>>())), 940 construct<IntrinsicTypeSpec>(construct<IntrinsicTypeSpec::Logical>( 941 "LOGICAL" >> noKindSelector))))}; 942 943 TYPE_PARSER(construct<ImplicitSpec>(declarationTypeSpec, 944 parenthesized(nonemptyList(Parser<LetterSpec>{}))) || 945 construct<ImplicitSpec>(implicitSpecDeclarationTypeSpecRetry, 946 parenthesized(nonemptyList(Parser<LetterSpec>{})))) 947 948 // R865 letter-spec -> letter [- letter] 949 TYPE_PARSER(space >> (construct<LetterSpec>(letter, maybe("-" >> letter)) || 950 construct<LetterSpec>(otherIdChar, 951 construct<std::optional<const char *>>()))) 952 953 // R867 import-stmt -> 954 // IMPORT [[::] import-name-list] | 955 // IMPORT , ONLY : import-name-list | IMPORT , NONE | IMPORT , ALL 956 TYPE_CONTEXT_PARSER("IMPORT statement"_en_US, 957 construct<ImportStmt>( 958 "IMPORT , ONLY :" >> pure(common::ImportKind::Only), listOfNames) || 959 construct<ImportStmt>( 960 "IMPORT , NONE" >> pure(common::ImportKind::None)) || 961 construct<ImportStmt>( 962 "IMPORT , ALL" >> pure(common::ImportKind::All)) || 963 construct<ImportStmt>( 964 "IMPORT" >> maybe("::"_tok) >> optionalList(name))) 965 966 // R868 namelist-stmt -> 967 // NAMELIST / namelist-group-name / namelist-group-object-list 968 // [[,] / namelist-group-name / namelist-group-object-list]... 969 // R869 namelist-group-object -> variable-name 970 TYPE_PARSER(construct<NamelistStmt>("NAMELIST" >> 971 nonemptySeparated( 972 construct<NamelistStmt::Group>("/" >> name / "/", listOfNames), 973 maybe(","_tok)))) 974 975 // R870 equivalence-stmt -> EQUIVALENCE equivalence-set-list 976 // R871 equivalence-set -> ( equivalence-object , equivalence-object-list ) 977 TYPE_PARSER(construct<EquivalenceStmt>("EQUIVALENCE" >> 978 nonemptyList( 979 parenthesized(nonemptyList("expected EQUIVALENCE objects"_err_en_US, 980 Parser<EquivalenceObject>{}))))) 981 982 // R872 equivalence-object -> variable-name | array-element | substring 983 TYPE_PARSER(construct<EquivalenceObject>(indirect(designator))) 984 985 // R873 common-stmt -> 986 // COMMON [/ [common-block-name] /] common-block-object-list 987 // [[,] / [common-block-name] / common-block-object-list]... 988 TYPE_PARSER( 989 construct<CommonStmt>("COMMON" >> defaulted("/" >> maybe(name) / "/"), 990 nonemptyList("expected COMMON block objects"_err_en_US, 991 Parser<CommonBlockObject>{}), 992 many(maybe(","_tok) >> 993 construct<CommonStmt::Block>("/" >> maybe(name) / "/", 994 nonemptyList("expected COMMON block objects"_err_en_US, 995 Parser<CommonBlockObject>{}))))) 996 997 // R874 common-block-object -> variable-name [( array-spec )] 998 TYPE_PARSER(construct<CommonBlockObject>(name, maybe(arraySpec))) 999 1000 // R901 designator -> object-name | array-element | array-section | 1001 // coindexed-named-object | complex-part-designator | 1002 // structure-component | substring 1003 // The Standard's productions for designator and its alternatives are 1004 // ambiguous without recourse to a symbol table. Many of the alternatives 1005 // for designator (viz., array-element, coindexed-named-object, 1006 // and structure-component) are all syntactically just data-ref. 1007 // What designator boils down to is this: 1008 // It starts with either a name or a character literal. 1009 // If it starts with a character literal, it must be a substring. 1010 // If it starts with a name, it's a sequence of %-separated parts; 1011 // each part is a name, maybe a (section-subscript-list), and 1012 // maybe an [image-selector]. 1013 // If it's a substring, it ends with (substring-range). 1014 TYPE_CONTEXT_PARSER("designator"_en_US, 1015 sourced(construct<Designator>(substring) || construct<Designator>(dataRef))) 1016 1017 constexpr auto percentOrDot{"%"_tok || 1018 // legacy VAX extension for RECORD field access 1019 extension<LanguageFeature::DECStructures>( 1020 "."_tok / lookAhead(OldStructureComponentName{}))}; 1021 1022 // R902 variable -> designator | function-reference 1023 // This production appears to be left-recursive in the grammar via 1024 // function-reference -> procedure-designator -> proc-component-ref -> 1025 // scalar-variable 1026 // and would be so if we were to allow functions to be called via procedure 1027 // pointer components within derived type results of other function references 1028 // (a reasonable extension, esp. in the case of procedure pointer components 1029 // that are NOPASS). However, Fortran constrains the use of a variable in a 1030 // proc-component-ref to be a data-ref without coindices (C1027). 1031 // Some array element references will be misrecognized as function references. 1032 constexpr auto noMoreAddressing{!"("_tok >> !"["_tok >> !percentOrDot}; 1033 TYPE_CONTEXT_PARSER("variable"_en_US, 1034 construct<Variable>(indirect(functionReference / noMoreAddressing)) || 1035 construct<Variable>(indirect(designator))) 1036 1037 // R908 substring -> parent-string ( substring-range ) 1038 // R909 parent-string -> 1039 // scalar-variable-name | array-element | coindexed-named-object | 1040 // scalar-structure-component | scalar-char-literal-constant | 1041 // scalar-named-constant 1042 TYPE_PARSER( 1043 construct<Substring>(dataRef, parenthesized(Parser<SubstringRange>{}))) 1044 1045 TYPE_PARSER(construct<CharLiteralConstantSubstring>( 1046 charLiteralConstant, parenthesized(Parser<SubstringRange>{}))) 1047 1048 // R910 substring-range -> [scalar-int-expr] : [scalar-int-expr] 1049 TYPE_PARSER(construct<SubstringRange>( 1050 maybe(scalarIntExpr), ":" >> maybe(scalarIntExpr))) 1051 1052 // R911 data-ref -> part-ref [% part-ref]... 1053 // R914 coindexed-named-object -> data-ref 1054 // R917 array-element -> data-ref 1055 TYPE_PARSER( 1056 construct<DataRef>(nonemptySeparated(Parser<PartRef>{}, percentOrDot))) 1057 1058 // R912 part-ref -> part-name [( section-subscript-list )] [image-selector] 1059 TYPE_PARSER(construct<PartRef>(name, 1060 defaulted( 1061 parenthesized(nonemptyList(Parser<SectionSubscript>{})) / !"=>"_tok), 1062 maybe(Parser<ImageSelector>{}))) 1063 1064 // R913 structure-component -> data-ref 1065 TYPE_PARSER(construct<StructureComponent>( 1066 construct<DataRef>(some(Parser<PartRef>{} / percentOrDot)), name)) 1067 1068 // R919 subscript -> scalar-int-expr 1069 constexpr auto subscript{scalarIntExpr}; 1070 1071 // R920 section-subscript -> subscript | subscript-triplet | vector-subscript 1072 // R923 vector-subscript -> int-expr 1073 // N.B. The distinction that needs to be made between "subscript" and 1074 // "vector-subscript" is deferred to semantic analysis. 1075 TYPE_PARSER(construct<SectionSubscript>(Parser<SubscriptTriplet>{}) || 1076 construct<SectionSubscript>(intExpr)) 1077 1078 // R921 subscript-triplet -> [subscript] : [subscript] [: stride] 1079 TYPE_PARSER(construct<SubscriptTriplet>( 1080 maybe(subscript), ":" >> maybe(subscript), maybe(":" >> subscript))) 1081 1082 // R925 cosubscript -> scalar-int-expr 1083 constexpr auto cosubscript{scalarIntExpr}; 1084 1085 // R924 image-selector -> 1086 // lbracket cosubscript-list [, image-selector-spec-list] rbracket 1087 TYPE_CONTEXT_PARSER("image selector"_en_US, 1088 construct<ImageSelector>("[" >> nonemptyList(cosubscript / !"="_tok), 1089 defaulted("," >> nonemptyList(Parser<ImageSelectorSpec>{})) / "]")) 1090 1091 // R926 image-selector-spec -> 1092 // STAT = stat-variable | TEAM = team-value | 1093 // TEAM_NUMBER = scalar-int-expr 1094 TYPE_PARSER(construct<ImageSelectorSpec>(construct<ImageSelectorSpec::Stat>( 1095 "STAT =" >> scalar(integer(indirect(variable))))) || 1096 construct<ImageSelectorSpec>(construct<TeamValue>("TEAM =" >> teamValue)) || 1097 construct<ImageSelectorSpec>(construct<ImageSelectorSpec::Team_Number>( 1098 "TEAM_NUMBER =" >> scalarIntExpr))) 1099 1100 // R927 allocate-stmt -> 1101 // ALLOCATE ( [type-spec ::] allocation-list [, alloc-opt-list] ) 1102 TYPE_CONTEXT_PARSER("ALLOCATE statement"_en_US, 1103 construct<AllocateStmt>("ALLOCATE (" >> maybe(typeSpec / "::"), 1104 nonemptyList(Parser<Allocation>{}), 1105 defaulted("," >> nonemptyList(Parser<AllocOpt>{})) / ")")) 1106 1107 // R928 alloc-opt -> 1108 // ERRMSG = errmsg-variable | MOLD = source-expr | 1109 // SOURCE = source-expr | STAT = stat-variable 1110 // R931 source-expr -> expr 1111 TYPE_PARSER(construct<AllocOpt>( 1112 construct<AllocOpt::Mold>("MOLD =" >> indirect(expr))) || 1113 construct<AllocOpt>( 1114 construct<AllocOpt::Source>("SOURCE =" >> indirect(expr))) || 1115 construct<AllocOpt>(statOrErrmsg)) 1116 1117 // R929 stat-variable -> scalar-int-variable 1118 TYPE_PARSER(construct<StatVariable>(scalar(integer(variable)))) 1119 1120 // R932 allocation -> 1121 // allocate-object [( allocate-shape-spec-list )] 1122 // [lbracket allocate-coarray-spec rbracket] 1123 // TODO: allocate-shape-spec-list might be misrecognized as 1124 // the final list of subscripts in allocate-object. 1125 TYPE_PARSER(construct<Allocation>(Parser<AllocateObject>{}, 1126 defaulted(parenthesized(nonemptyList(Parser<AllocateShapeSpec>{}))), 1127 maybe(bracketed(Parser<AllocateCoarraySpec>{})))) 1128 1129 // R933 allocate-object -> variable-name | structure-component 1130 TYPE_PARSER(construct<AllocateObject>(structureComponent) || 1131 construct<AllocateObject>(name / !"="_tok)) 1132 1133 // R934 allocate-shape-spec -> [lower-bound-expr :] upper-bound-expr 1134 // R938 allocate-coshape-spec -> [lower-bound-expr :] upper-bound-expr 1135 TYPE_PARSER(construct<AllocateShapeSpec>(maybe(boundExpr / ":"), boundExpr)) 1136 1137 // R937 allocate-coarray-spec -> 1138 // [allocate-coshape-spec-list ,] [lower-bound-expr :] * 1139 TYPE_PARSER(construct<AllocateCoarraySpec>( 1140 defaulted(nonemptyList(Parser<AllocateShapeSpec>{}) / ","), 1141 maybe(boundExpr / ":") / "*")) 1142 1143 // R939 nullify-stmt -> NULLIFY ( pointer-object-list ) 1144 TYPE_CONTEXT_PARSER("NULLIFY statement"_en_US, 1145 "NULLIFY" >> parenthesized(construct<NullifyStmt>( 1146 nonemptyList(Parser<PointerObject>{})))) 1147 1148 // R940 pointer-object -> 1149 // variable-name | structure-component | proc-pointer-name 1150 TYPE_PARSER(construct<PointerObject>(structureComponent) || 1151 construct<PointerObject>(name)) 1152 1153 // R941 deallocate-stmt -> 1154 // DEALLOCATE ( allocate-object-list [, dealloc-opt-list] ) 1155 TYPE_CONTEXT_PARSER("DEALLOCATE statement"_en_US, 1156 construct<DeallocateStmt>( 1157 "DEALLOCATE (" >> nonemptyList(Parser<AllocateObject>{}), 1158 defaulted("," >> nonemptyList(statOrErrmsg)) / ")")) 1159 1160 // R942 dealloc-opt -> STAT = stat-variable | ERRMSG = errmsg-variable 1161 // R1165 sync-stat -> STAT = stat-variable | ERRMSG = errmsg-variable 1162 TYPE_PARSER(construct<StatOrErrmsg>("STAT =" >> statVariable) || 1163 construct<StatOrErrmsg>("ERRMSG =" >> msgVariable)) 1164 1165 // Directives, extensions, and deprecated statements 1166 // !DIR$ IGNORE_TKR [ [(tkr...)] name ]... 1167 // !DIR$ name... 1168 constexpr auto beginDirective{skipStuffBeforeStatement >> "!"_ch}; 1169 constexpr auto endDirective{space >> endOfLine}; 1170 constexpr auto ignore_tkr{ 1171 "DIR$ IGNORE_TKR" >> optionalList(construct<CompilerDirective::IgnoreTKR>( 1172 defaulted(parenthesized(some("tkr"_ch))), name))}; 1173 TYPE_PARSER( 1174 beginDirective >> sourced(construct<CompilerDirective>(ignore_tkr) || 1175 construct<CompilerDirective>("DIR$" >> many(name))) / 1176 endDirective) 1177 1178 TYPE_PARSER(extension<LanguageFeature::CrayPointer>(construct<BasedPointerStmt>( 1179 "POINTER" >> nonemptyList("expected POINTER associations"_err_en_US, 1180 construct<BasedPointer>("(" >> objectName / ",", 1181 objectName, maybe(Parser<ArraySpec>{}) / ")"))))) 1182 1183 TYPE_PARSER(construct<StructureStmt>("STRUCTURE /" >> name / "/", pure(true), 1184 optionalList(entityDecl)) || 1185 construct<StructureStmt>( 1186 "STRUCTURE" >> name, pure(false), defaulted(cut >> many(entityDecl)))) 1187 1188 TYPE_PARSER(construct<StructureField>(statement(StructureComponents{})) || 1189 construct<StructureField>(indirect(Parser<Union>{})) || 1190 construct<StructureField>(indirect(Parser<StructureDef>{}))) 1191 1192 TYPE_CONTEXT_PARSER("STRUCTURE definition"_en_US, 1193 extension<LanguageFeature::DECStructures>(construct<StructureDef>( 1194 statement(Parser<StructureStmt>{}), many(Parser<StructureField>{}), 1195 statement( 1196 construct<StructureDef::EndStructureStmt>("END STRUCTURE"_tok))))) 1197 1198 TYPE_CONTEXT_PARSER("UNION definition"_en_US, 1199 construct<Union>(statement(construct<Union::UnionStmt>("UNION"_tok)), 1200 many(Parser<Map>{}), 1201 statement(construct<Union::EndUnionStmt>("END UNION"_tok)))) 1202 1203 TYPE_CONTEXT_PARSER("MAP definition"_en_US, 1204 construct<Map>(statement(construct<Map::MapStmt>("MAP"_tok)), 1205 many(Parser<StructureField>{}), 1206 statement(construct<Map::EndMapStmt>("END MAP"_tok)))) 1207 1208 TYPE_CONTEXT_PARSER("arithmetic IF statement"_en_US, 1209 deprecated<LanguageFeature::ArithmeticIF>(construct<ArithmeticIfStmt>( 1210 "IF" >> parenthesized(expr), label / ",", label / ",", label))) 1211 1212 TYPE_CONTEXT_PARSER("ASSIGN statement"_en_US, 1213 deprecated<LanguageFeature::Assign>( 1214 construct<AssignStmt>("ASSIGN" >> label, "TO" >> name))) 1215 1216 TYPE_CONTEXT_PARSER("assigned GOTO statement"_en_US, 1217 deprecated<LanguageFeature::AssignedGOTO>(construct<AssignedGotoStmt>( 1218 "GO TO" >> name, 1219 defaulted(maybe(","_tok) >> 1220 parenthesized(nonemptyList("expected labels"_err_en_US, label)))))) 1221 1222 TYPE_CONTEXT_PARSER("PAUSE statement"_en_US, 1223 deprecated<LanguageFeature::Pause>( 1224 construct<PauseStmt>("PAUSE" >> maybe(Parser<StopCode>{})))) 1225 1226 // These requirement productions are defined by the Fortran standard but never 1227 // used directly by the grammar: 1228 // R620 delimiter -> ( | ) | / | [ | ] | (/ | /) 1229 // R1027 numeric-expr -> expr 1230 // R1031 int-constant-expr -> int-expr 1231 // R1221 dtv-type-spec -> TYPE ( derived-type-spec ) | 1232 // CLASS ( derived-type-spec ) 1233 // 1234 // These requirement productions are defined and used, but need not be 1235 // defined independently here in this file: 1236 // R771 lbracket -> [ 1237 // R772 rbracket -> ] 1238 // 1239 // Further note that: 1240 // R607 int-constant -> constant 1241 // is used only once via R844 scalar-int-constant 1242 // R904 logical-variable -> variable 1243 // is used only via scalar-logical-variable 1244 // R906 default-char-variable -> variable 1245 // is used only via scalar-default-char-variable 1246 // R907 int-variable -> variable 1247 // is used only via scalar-int-variable 1248 // R915 complex-part-designator -> designator % RE | designator % IM 1249 // %RE and %IM are initially recognized as structure components 1250 // R916 type-param-inquiry -> designator % type-param-name 1251 // is occulted by structure component designators 1252 // R918 array-section -> 1253 // data-ref [( substring-range )] | complex-part-designator 1254 // is not used because parsing is not sensitive to rank 1255 // R1030 default-char-constant-expr -> default-char-expr 1256 // is only used via scalar-default-char-constant-expr 1257 } // namespace Fortran::parser 1258